如何按字段分组并在codefirst中汇总另一个字段?

时间:2016-07-11 16:33:12

标签: c# linq

我有一个包含2个字段的库存模型列表。例如。

库存模式

public class stock
{
   public int Id{get;set;}
   public string product{get;set;}
   public decimal stock{get;set;}
}

我想通过linq.any帮助首先按产品分类和总计代码?

1 个答案:

答案 0 :(得分:2)

假设您拥有这些Stock个对象的集合,您可以使用Select()方法以及GroupBy()Sum()来检索您要查找的内容:

// This will group each of your elements by their product value and project each of these
// groups to an object that stores the product and the sum of the stock properties for that
// group.
var totals = products.GroupBy(p => p.product)
                     .Select(p => new { Product = p.Key, Stock = p.Sum(x => x.stock) })
                     .ToList();

你可以see a working example using your provided input here