相关文章推荐
大力的核桃  ·  JAVA ...·  1 年前    · 
知识渊博的帽子  ·  vscode ...·  1 年前    · 

LINQ按多列分组(Group By)并计算总和(Sum)

SQL语句:

SELECT * FROM <TableName> GROUP BY <Column1>,<Column2>
QuantityBreakdown
    MaterialID int,
    ProductID int,
    Quantity float
INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

在C#中,如何使用LINQ实现以上SQL语句中的需求呢?方式归纳如下:

var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();
from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),
var Results= query.GroupBy(x => new { x.Column1, x.Column2 });

易错提醒:

grp.Key.ProductID, //前往不要忘了Key!!!
Quantity = grp.Sum(t => t.Quantity) //必须取别名Quantity !!!

C# list集合对多个字段group by 、并新增字段

void Main()
     var  empList =new List<Employee>
        new Employee {ID = 1, FName = "John", Age = 23, Sex = 'M'},
        new Employee {ID = 2, FName = "Mary", Age = 25, Sex = 'F'},
        new Employee {ID = 3, FName = "Amber", Age = 23, Sex = 'M'},
        new Employee {ID = 4, FName = "Kathy", Age = 25, Sex = 'F'},
        new Employee {ID = 5, FName = "Lena", Age = 27, Sex = 'F'},
        new Employee {ID = 6, FName = "Bill", Age = 28, Sex = 'M'},
        new Employee {ID = 7, FName = "Celina", Age = 27, Sex = 'F'},
        new Employee {ID = 8, FName = "John", Age = 28, Sex = 'M'}
    // query with lamda expression g.Key代表Age和Sex两字段,Count为新增字段<br>        // 最终返回的集合QueryWithLamda包含字段:Age、Sex、Count
    var QueryWithLamda = empList.GroupBy(x => new { x.Age,  x.Sex})
                .Select(g=>new {g.Key, Count=g.Count()});
    //query with standard expression<br>        //返回结果同上
    var query=from el in empList
              group el by new {el.Age,el.Sex} into g
              select new {g.Key, Count=g.Count()};
    foreach (var employee in query /* Or  QueryWithLamda */ )
             Console.WriteLine(employee.Count);
public class Employee
  public int ID {get;set;}
  public string FName {get;set;}
  public int Age {get;set;}
  public char Sex {get;set;}

Linq 中按照多个值进行分组(GroupBy)

/// <summary>要查询的对象</summary>
class Employee {
   public int ID { get;set; }
   public string FName { get; set; }
   public int Age { get; set; }
   public char Sex { get; set; }

如果对这个类的AgeSex的连个字段进行分组,方法如下:

// 先造一些数据
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() {
   ID = 1, FName = "John", Age = 23, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 2, FName = "Mary", Age = 25, Sex = 'F'
});
empList.Add(new Employee() {
   ID = 3, FName = "Amber", Age = 23, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 4, FName = "Kathy", Age = 25, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 5, FName = "Lena", Age = 27, Sex = 'F'
});
empList.Add(new Employee() {
   ID = 6, FName = "Bill", Age = 28, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 7, FName = "Celina", Age = 27, Sex = 'F'
});
empList.Add(new Employee() {
   ID = 8, FName = "John", Age = 28, Sex = 'M'
});

接下来的做法是:

// 实现多key分组的扩展函数版本
var sums = empList
         .GroupBy(x => new { x.Age, x.Sex })
         .Select(group => new {
            Peo = group.Key, Count = group.Count()
         });
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);
// 实现多key分组的lambda版本
var sums2 = from emp in empList
            group emp by new { emp.Age, emp.Sex } into g
            select new { Peo = g.Key, Count = g.Count() };
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);

这个例子中就充分利用了匿名类型。

LINQ按多列分组(Group By)并计算总和(Sum)SQL语句:SELECT * FROM &lt;TableName&gt; GROUP BY &lt;Column1&gt;,&lt;Column2&gt;QuantityBreakdown( MaterialID int, ProductID int, Quantity float)INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
var deGroup = from tt in list where tt.WZ_TYPE_ID == 0 group tt by new { tt.SCTYPE_ID, tt.SCTYPE_IDNAME } into qq select new SCTYPE_ID = qq.Key.SCTYPE_I..
static void Main( string[] args ) int[] intNumbers = new int[] { 1, 4, 3, 4 }; float[] floatNumbers = new float public string goodType { get; set; } public string goodName { get; set; } public int price { get; set; }
  在Linq中有一些这样的操作,根据集合计算某一单一值,比如集合的最大值,最小值,平均值等等。Linq中包含7种操作,这7种操作被称作聚合操作。 1、Count操作,计算序列中元素的个数,或者计算满足一定条件的元素的个数 2、Sum操作,计算序列中所有元素的值的总和 3、Max操作,计算序列中元素的最大值 4、Min操作,计算序列中元素的最小值 5、Average操作,计算序列中所有元...
var data = Db.SqlQueryable<GPS_WY_DataTrend>(sqlstr); //根据STCD分组 然后汇总每组的HorizontalWY值 var groupdata=data.GroupBy(t => t.STCD).Select(t=>new { STCD=t.STCD, HorizontalWY =SqlFunc.AggregateSum(t.HorizontalWY)}).OrderBy(t=>t.HorizontalWY,OrderBy
LINQ和Lambda都是C#编程语言的功能,但它们有不同的用途。 LINQ是一个查询语言,允许您使用类似于SQL的语法查询各种数据源,例如数据库、集合、XML文档等。使用LINQ可以更容易地查询和处理数据,从而减少了编写大量循环和条件语句的代码。 Lambda是一种表达式,用于创建匿名方法或委托。Lambda表达式通常用于LINQ查询中作为筛选器、选择器或排序器。它允许您更轻松地编写匿名函数,并且可以提高代码的可读性和可维护性。 因此,虽然LINQ和Lambda经常一起使用,但它们有不同的功能和用途。LINQ用于查询和处理数据,而Lambda用于编写匿名方法和委托。