在Linq中使用空值的自连接c#
本文关键字:自连接 空值 Linq | 更新日期: 2023-09-27 18:11:34
我怎么能得到有空的行用于自连接的列?我的代码是:
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
。是否有一种方法,我可以得到所有的行?
备选语法:
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
});
我从这里通过应用左连接找到了解决方案:
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