【发布时间】:2015-01-02 00:47:48
【问题描述】:
我有一个包含在名为 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
};
以上是我尝试过的,但是如果缺少地址,我将无法获得有关分支的信息...我仍在尝试弄清楚如何使用 Linq 进行此操作。在 SQL 中,我将刚刚加入这两个表以获取该信息。
谁能帮我解决这个问题...我敢肯定这是一件很容易的事情。谢谢。 PS。我知道这与 (Linq query to return a flatened list of parent child) 非常相似,但其中的孩子始终存在。
编辑 - 工作解决方案 以下是似乎对我有用的代码。我无法针对源数据库使用数据库,因为 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
};
感谢您的帮助。这些链接确实帮助我理解了需要发生的事情。
我还尝试了 Daniel Brü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
}));
【问题讨论】: