首页 > 解决方案 > 动态 GroupBy LINQ

问题描述

假设我有一堂课

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

我想像这样使用 group by;

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)
              };

我如何使用表达式树来做到这一点

标签: c#linqgroup-byexpression-trees

解决方案


欢迎来到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)
         }

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


推荐阅读