Linq离开了3桌

时间:2017-10-17 16:23:25

标签: c# linq left-join

我试图将以下查询翻译成lambda表达式

var results = (from g in _groups
         join cr in _categoryRoots on g.Id equals cr.Group_Id into gcr
         from lgc in gcr.DefaultIfEmpty(new CategoryRoot())
         join c in _categories on lgc.Id equals c.CategoryRoot_Id into ccr
         from lccr in ccr.DefaultIfEmpty()
         select new GroupCategory
         {
             Id = g.Id,
             Name = g.Name,
             CategoryRoot_Id = lgc == null ? 0: lgc.Id,
             CategoryRootName = lgc == null ? "": lgc.Name,
             Category_Id = lccr == null ? 0: lccr.Id,
             CategoryName = lccr == null ? "": lccr.Name
         }).ToList();

想要改成以下内容。

var rs = _groups.Join(_categoryRoots, g => g.Id, cr => cr.Group_Id, (g, cr) => new GroupCategory { Id = g.Id, Name = g.Name, CategoryRoot_Id = cr.Id, CategoryRootName = cr.Name  });

运行代码示例https://dotnetfiddle.net/A3AO0V

1 个答案:

答案 0 :(得分:0)

我不明白你真正的问题,但我只想分享一种简化查询的方法。如果这样做的话,左连接就不那么混乱了:

var results = (from g in _groups
               from lgc in _categoryRoots.Where(cr => g.Id == cr.Group_Id).DefaultIfEmpty(new CategoryRoot())
               from lccr in _categories.Where(c => lgc.Id == c.CategoryRoot_Id).DefaultIfEmpty()
               select new GroupCategory
               {
                   Id = g.Id,
                   Name = g.Name,
                   CategoryRoot_Id = lgc?.Id ?? 0,
                   CategoryRootName = lgc?.Name ?? "",
                   Category_Id = lccr?.Id ?? ',
                   CategoryName = lccr?.Name ?? ""
               }).ToList();

如果您至少使用C#6(VS 2015),您可以利用空合并运算符?.来简化这些空检查。