LEFT OUTER JOIN in LINQ

后端 未结 22 2454
臣服心动
臣服心动 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:33

    There are three tables: persons, schools and persons_schools, which connects persons to the schools they study in. A reference to the person with id=6 is absent in the table persons_schools. However the person with id=6 is presented in the result lef-joined grid.

    List persons = new List
    {
        new Person { id = 1, name = "Alex", phone = "4235234" },
        new Person { id = 2, name = "Bob", phone = "0014352" },
        new Person { id = 3, name = "Sam", phone = "1345" },
        new Person { id = 4, name = "Den", phone = "3453452" },
        new Person { id = 5, name = "Alen", phone = "0353012" },
        new Person { id = 6, name = "Simon", phone = "0353012" }
    };
    
    List schools = new List
    {
        new School { id = 1, name = "Saint. John's school"},
        new School { id = 2, name = "Public School 200"},
        new School { id = 3, name = "Public School 203"}
    };
    
    List persons_schools = new List
    {
        new PersonSchool{id_person = 1, id_school = 1},
        new PersonSchool{id_person = 2, id_school = 2},
        new PersonSchool{id_person = 3, id_school = 3},
        new PersonSchool{id_person = 4, id_school = 1},
        new PersonSchool{id_person = 5, id_school = 2}
        //a relation to the person with id=6 is absent
    };
    
    var query = from person in persons
                join person_school in persons_schools on person.id equals person_school.id_person
                into persons_schools_joined
                from person_school_joined in persons_schools_joined.DefaultIfEmpty()
                from school in schools.Where(var_school => person_school_joined == null ? false : var_school.id == person_school_joined.id_school).DefaultIfEmpty()
                select new { Person = person.name, School = school == null ? String.Empty : school.name };
    
    foreach (var elem in query)
    {
        System.Console.WriteLine("{0},{1}", elem.Person, elem.School);
    }
    

提交回复
热议问题