LINQ:获取父对象属性和单个子属性作为扁平结构
问题描述:
我有一个名为分支的父对象中包含的地址列表。分支可能会或可能不会定义这些地址,我需要得到一个扁平的层次结构或这些分支和地址。LINQ:获取父对象属性和单个子属性作为扁平结构
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
};
谢谢你的帮助。这些链接确实帮助我了解需要发生的事情。
我也试过丹尼尔布鲁克纳的解决方案,看起来更优雅,需要更少的打字。 :-)似乎在我尝试过的情景中工作。
这是看起来像什么。
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 }));
答
对不起,可能是我很晚 - 但我遇到了类似的问题,但没有找到这个帖子甚至5.5年后一个具体的答案。我的解决方案(未优化 - 但工作):
public class YearDayBill
{
public string Name;
public int YearDay;
}
public class EatOutDaysOfYear
{
public string Name;
public List<int> YearDays;
}
public static class Program
{
static void Main()
{
var eatouts = new List<EatOutDaysOfYear>
{
new EatOutDaysOfYear {Name = "amit", YearDays = new List<int>() {59, 37, 31, 17, 29}},
new EatOutDaysOfYear {Name = "prakash", YearDays = new List<int>() {6, 18, 13}},
new EatOutDaysOfYear {Name = "sarvo", YearDays = new List<int>() {9, 7, 47, 56, 82, 96}},
new EatOutDaysOfYear {Name = "akshay", YearDays = new List<int>() {8, 5, 2, 4}}
};
// query to get properties of parent ('Name') and single child element
var bills = eatouts
.SelectMany(a => a.YearDays
.Select(b => new YearDayBill {Name = a.Name, YearDay = b}))
.OrderBy(d => d.Name) // optional
.ThenBy(e => e.YearDay) // optional
.ToList();
bills.ForEach(a => Console.WriteLine(string.Concat(a.Name, " | ", a.YearDay)));
}
}