[C#] Linq – Left outer join (with Method chain)

var characters = new[] {
    new Character { name = "Hero", inventory_id    = 1 },
    new Character { name = "Heroine", inventory_id = 2 },
};

var items = new[] {
    new Item { inventory_id = 2, name = "Weapon" },
    new Item { inventory_id = 2, name = "Armor" },
};

var joined = characters
    .GroupJoin(
        items,
        c => c.inventory_id,
        i => i.inventory_id,
        (character, item) => (character, item: item.DefaultIfEmpty()));

foreach (var elem in joined) {
    foreach (var ci in elem.item) {
        WriteLine($"{elem.character.name} has {ci?.name ?? "no item"}");
    }
}

Output

Hero has no item
Heroine has Weapon
Heroine has Armor

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다