由LINQ动态分组

时间:2019-03-18 18:12:27

标签: c# linq group-by expression-trees

假设我有一堂课

public class Item
{ 
    public int Field1{get;set;}
    ……
    public int FieldN{get;set;}
}

我想这样使用分组方式;

Collection.GroupBy(selector“Field1,…,FieldK”)
          .Select(x=> new Item
              {
                  Field1 = x.Key.Field1,
                   …
                  FieldK= x.Key.FieldK,
                  FiledK+1= x.Sum(x.FieldK+1),
                  ….
                  FiledN= x.Sum(x.FieldN)
              };

如何使用Expresions树做到这一点

1 个答案:

答案 0 :(得分:0)

欢迎来到stackoverflow mahul! 您想要的可以这样实现:

var a = from item in collection
        group item by new {item.Field1, ... , item.Fieldk} into newGroup
        select new {
            Field1 = newGroup.Key.Field1
            Field2 = newGroup.Key.Field1
            ...
            FieldK+1 = newGroup.Sum(x => x.FieldK+1),
            ...
            FieldN = newGroiup.Sum(x => x.FieldN)
         }

确保也阅读documentation。那里有很好的例子。