我有一个地址列表,包含在名为 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 中,我将刚刚加入两个表以获取该信息。
谁能帮我解决这个问题...我相信这很容易。谢谢。附言。我知道这与 ( Linq query to return a flatened list of parent child ) 非常相似,但在那个 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
}));
最佳答案
IQueryable<Branch> branches = GetBranches();
var result = braches.
SelectMany(b => b.Addresses.
DefaultIfEmpty().
Select(a => new { Branch = b, Address = a }));
关于c# - LINQ:获取父对象属性和单个子属性作为平面结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/799118/