任何人都可以解释如何将这个LINQ查询简化为多行吗?
Data.StoredItems.GroupBy(i => i.Name, ((name, cps) => new { Name = name, Components = cps.Where(cp => cp.Name == name).GroupBy(cp => cp.Type, (type, components) => new { Type = type, List = components.ToList() }).ToList() }))
答案 0 :(得分:1)
如果目标是使其更具可读性,那么您可以这样做:
Data.StoredItems
.GroupBy(
i => i.Name,
((name, cps) => new
{
Name = name,
Components =
cps //.Where(cp => cp.Name == name) This Where call here is redundant
.GroupBy(
cp => cp.Type,
(type, components) => new
{
Type = type,
List = components.ToList()
})
.ToList()
}))
请注意,我删除了Where
,因为不需要它。 cps
中的项目已经Name
等于name
。
答案 1 :(得分:0)
在每个。[方法调用],你只需将它存储在一个集合中,然后继续下一行的链。
例如:
var query = Data.StoredItems
var query2 = query.GroupBy(i => i.Name,((name,cps)=> new {Name = name,Components = cps.Where(cp => cp.Name == name)
并继续从那里开始。
如果只是为了调试,我可能会建议您考虑编写一个“窥视”代码。喜欢:
.ForEach(item => Console.WriteLine(item.toString);
https://www.simple-talk.com/dotnet/.net-framework/linq-secrets-revealed-chaining-and-debugging/