2

我有一个嵌套的对象列表。我需要分组依据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();
4

4 回答 4

5

SelectMany接受 anIEnumerable<SomethingWithAnIEnumerable>并将所有SomethingWithAnIEnumerable选定IEnumerable的 s 展平为一个 s IEnumerable

nestedList = groupedData.SelectMany(pa => pa.nestedList).ToList()
于 2012-12-06T15:53:45.607 回答
5

我认为这将解决您的问题。

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();
于 2012-12-07T08:09:14.063 回答
1

使用SelectMany

如果您想将列表分组为一种用途

nestedList = groupedData.SelectMany(d=>d.nestedList)

如果您想要Sum该列表,请使用

nestedList = groupedData.SelectMany(d=>d.nestedList).Sum(o=>o.otherNumber)
于 2012-12-06T15:52:15.723 回答
0

我认为您的 IdentfierB 可能是某种键,您的结果应该反映 Grouped 和 Summed TypeB。

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)
      }
  }
于 2012-12-06T20:06:15.430 回答