我有一个嵌套的对象列表。我需要按identifierA
和Sum
对其数字属性进行分组,嵌套列表应分别分组:
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; }
}
所以我期待这样的事情:
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();
答案 0 :(得分:5)
SelectMany
获取IEnumerable<SomethingWithAnIEnumerable>
并将所有SomethingWithAnIEnumerable
个选定的IEnumerable
展平为一个IEnumerable
:
nestedList = groupedData.SelectMany(pa => pa.nestedList).ToList()
答案 1 :(得分:4)
我认为这可以解决您的问题。
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();
答案 2 :(得分:1)
如果您想将列表分组为一次使用
nestedList = groupedData.SelectMany(d=>d.nestedList)
如果您想要该列表的Sum
,请使用
nestedList = groupedData.SelectMany(d=>d.nestedList).Sum(o=>o.otherNumber)
答案 3 :(得分:0)
我认为你的IdentfierB可能是某种键,你的结果应该反映出Grouped和Summed TypeBs。
List<TypeA> groupedList = TypeAList
.GroupBy(a => a.identifierA)
.Select(g => new TypeA()
{
identierA = g.Key,
number = g.Sum(a => a.number)
nestedList = g.SelectMany(a => a.nestedList)
.GroupBy(b => b.identifierB)
.Select(g2 => new TypeB()
{
identifierB = g2.Key,
otherNumber = g2.Sum(b => b.otherNumber)
}
}