LEFT OUTER JOIN in LINQ

后端 未结 22 2449
臣服心动
臣服心动 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:15

    I would like to add that if you get the MoreLinq extension there is now support for both homogenous and heterogeneous left joins now

    http://morelinq.github.io/2.8/ref/api/html/Overload_MoreLinq_MoreEnumerable_LeftJoin.htm

    example:

    //Pretend a ClientCompany object and an Employee object both have a ClientCompanyID key on them
    
    return DataContext.ClientCompany
        .LeftJoin(DataContext.Employees,                         //Table being joined
            company => company.ClientCompanyID,                  //First key
            employee => employee.ClientCompanyID,                //Second Key
            company => new {company, employee = (Employee)null}, //Result selector when there isn't a match
            (company, employee) => new { company, employee });   //Result selector when there is a match
    

    EDIT:

    In retrospect this may work, but it converts the IQueryable to an IEnumerable as morelinq does not convert the query to SQL.

    You can instead use a GroupJoin as described here: https://stackoverflow.com/a/24273804/4251433

    This will ensure that it stays as an IQueryable in case you need to do further logical operations on it later.

提交回复
热议问题