LINQ:获取Parent对象属性和单个子属性作为平面结构

Abo*_*Dev 3 c# linq

我有一个名为Branch的父对象中包含的地址列表.分支可能会也可能不会定义这些地址,我需要获得一个扁平的层次结构或这些分支和地址.

var x = from p in CurrentBranchList 
        where p.ScheduledForDeletion == false
        from c in p.Addresses 
        where c.ScheduledForDeletion == false && c.AddressTypeId == 3
        select new
        {
          BranchId = p.BranchId,
          Name = p.Name,
          Address = (c == null) ? "" : c.Address1 + " " + c.Address2,
          City = (c == null) ? "" : c.City,
          State = (c == null) ? 0 : c.StateId
        };
Run Code Online (Sandbox Code Playgroud)

以上就是我尝试的但是如果地址丢失了,我得不到关于分支的信息...我还在试图弄清楚如何使用Linq.在SQL中我会离开加入两个表来获取该信息.

任何人都可以帮助我...我相信这是一件非常容易的事情.谢谢.PS.我知道这非常相似(Linq查询返回父子项的已分级列表)但在该项中,子项始终存在.


编辑 - 工作解决方案 以下代码似乎对我有用.我不能反对源数据库,因为CurrentBranchList中包含的对象是在内存中编辑的,并且持久性是在单个操作中执行的.

var x = from p in CurrentBranchList
        join c in CurrentBranchList.SelectMany(b => b.Addresses) 
          on p.EntityId equals c.EntityId into ur 
        where p.ScheduledForDeletion == false      
        from u in ur.DefaultIfEmpty() 
        select new
        {
          BranchId = p.BranchId,
          Name = p.Name,
          Address = (u == null) ? "" : u.Address1 + " " + u.Address2,
          City = (u == null) ? "" : u.City,
          State = (u == null) ? 0 : u.StateId
        };
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助.这些链接确实帮助我理解了需要发生的事情.

我也试过了DanielBrückner的解决方案,看起来更优雅,更少打字.:-)似乎在我试过的几个场景中工作.

这就是它的样子.

var xx = CurrentBranchList.SelectMany(b => b.Addresses.DefaultIfEmpty().Select(a => new 
        {
          BranchId = b.BranchId,
          Name = b.Name,
          Address = (a == null) ? "" : a.Address1 + " " + a.Address2,
          City = (a == null) ? "" : a.City,
          State = (a == null) ? 0 : a.StateId
        }));
Run Code Online (Sandbox Code Playgroud)

Dan*_*ner 5

IQueryable<Branch> branches = GetBranches();

var result = braches.
   SelectMany(b => b.Addresses.
      DefaultIfEmpty().
      Select(a => new { Branch = b, Address = a }));
Run Code Online (Sandbox Code Playgroud)