自我加入Linq,空值为c#

时间:2014-07-04 18:34:59

标签: c# sql linq self-join

如何获取用于自联接的列中具有null的行? 我的代码是:

IEnumerable<ListClassView> list = from l in lists join lp in lists on 
l.ParentListId equals lp.Id 
select new ListClassView()
{
    Id = l.Id,
    ListName = l.ListName,
    Description = l.Description,
    ParentName = lp.ListName,
    IsActive = l.IsActive
};

我无法获取ParentListId=null的行。有没有办法可以获得所有行?

2 个答案:

答案 0 :(得分:1)

替代语法:

var list = lists.GroupJoin(
  lists,
  l => l.ParentListId,
  lp => lp.Id,
  (l, lp) => new ListClassView
            { 
               Id = l.Id, 
               ListName = l.ListName, 
               Description = l.Description,
               ParentName = lp.FirstOrDefault() == null ? null : lp.First().ListName,
               IsActive = l.IsActive
            });

答案 1 :(得分:0)

我通过应用左连接找到了解决方案from here

IEnumerable<ListClassView> list = from l in lists join lp in lists on 
l.ParentListId equals lp.Id into lpp
from p in lpp.DefaultIfEmpty()
select new ListClassView()
{
    Id = l.Id,
    ListName = l.ListName,
    Description = l.Description,
    ParentName = p.ListName,
    IsActive = l.IsActive
};

现在,它获取所有行,包括ParentListId = null

的行