组嵌套使用LINQ名单 [英] Group nested list with linq
本文介绍了组嵌套使用LINQ名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象的嵌套列表。我需要按 identifierA
和总和
的数值属性,嵌套表应当分别组:
公共类类型A
{
公共字符串identifierA {搞定;组; }
公众的Int32号{搞定;组; }
公开名单<&的TypeB GT; nestedList {搞定;组; }
}
公共类的TypeB
{
公共字符串identifierB {搞定;组; }
公众的Int32 otherNumber {搞定;组; }
}
所以,我希望是这样的:
VAR名单<&类型A GT; groupedList =(由a.identifierA
A在TypeAList
组进入groupedData
选择新的类型A
{
identifierA = groupedData.Key,
号= groupedData.Sum(G => g.number),
nestedList = //如何分组嵌套PART
})了ToList()?。
解决方案
我认为这将解决您的问题。
列表<&类型A GT;列表= TypeAList
.GroupBy(A => a.identifierA)
。选择(
G = GT;
新类型A
{
identifierA = G 。重点,
号= g.Sum(N => n.number),
nestedList =
g.SelectMany(L => l.nestedList)
.GroupBy (b = GT; b.identifierB)
。选择(
GG =>
的TypeB新
{
identifierB = gg.Key,
otherNumber = gg.Sum(b = GT; b.otherNumber)
})了ToList()
})了ToList()。
I have a nested list of objects. That I need to group by identifierA
and Sum
its numeric properties, nested list shall group respectively:
public class TypeA
{
public String identifierA{ get; set; }
public Int32 number { get; set; }
public List<TypeB> nestedList { get; set; }
}
public class TypeB
{
public String identifierB { get; set; }
public Int32 otherNumber { get; set; }
}
So I'm expecting something like this:
var List<TypeA> groupedList = (from a in TypeAList
group a by a.identifierA
into groupedData
select new TypeA
{
identifierA = groupedData.Key,
number = groupedData.Sum(g => g.number ),
nestedList = //HOW TO GROUP NESTED PART?
}).ToList();
解决方案
I think that this will resolve your issue.
List<TypeA> list = TypeAList
.GroupBy(a => a.identifierA)
.Select(
g =>
new TypeA
{
identifierA = g.Key,
number = g.Sum(n => n.number),
nestedList =
g.SelectMany(l => l.nestedList)
.GroupBy(b => b.identifierB)
.Select(
gg =>
new TypeB
{
identifierB = gg.Key,
otherNumber = gg.Sum(b => b.otherNumber)
}).ToList()
}).ToList();
这篇关于组嵌套使用LINQ名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文