LEFT OUTER JOIN in LINQ

后端 未结 22 2514
臣服心动
臣服心动 2020-11-21 04:49

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Corr

22条回答
  •  执念已碎
    2020-11-21 05:18

    As per my answer to a similar question, here:

    Linq to SQL left outer join using Lambda syntax and joining on 2 columns (composite join key)

    Get the code here, or clone my github repo, and play!

    Query:

            var petOwners =
                from person in People
                join pet in Pets
                on new
                {
                    person.Id,
                    person.Age,
                }
                equals new
                {
                    pet.Id,
                    Age = pet.Age * 2, // owner is twice age of pet
                }
                into pets
                from pet in pets.DefaultIfEmpty()
                select new PetOwner
                {
                    Person = person,
                    Pet = pet,
                };
    

    Lambda:

            var petOwners = People.GroupJoin(
                Pets,
                person => new { person.Id, person.Age },
                pet => new { pet.Id, Age = pet.Age * 2 },
                (person, pet) => new
                {
                    Person = person,
                    Pets = pet,
                }).SelectMany(
                pet => pet.Pets.DefaultIfEmpty(),
                (people, pet) => new
                {
                    people.Person,
                    Pet = pet,
                });
    

提交回复
热议问题