相关疑难解决方法(0)

Linq:GroupBy,Sum和Count

我有一系列产品

public class Product {

   public Product() { }

   public string ProductCode {get; set;}
   public decimal Price {get; set; }
   public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

现在,我想根据产品代码对集合进行分组,并返回一个对象,其中包含每个代码的名称,数量或产品以及每个产品的总价格.

public class ResultLine{

   public ResultLine() { }

   public string ProductName {get; set;}
   public string Price {get; set; }
   public string Quantity {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

所以我使用GroupBy按ProductCode进行分组,然后计算总和并计算每个产品代码的记录数.

这是我到目前为止:

List<Product> Lines = LoadProducts();    
List<ResultLine> result = Lines
                .GroupBy(l => l.ProductCode)
                .SelectMany(cl => cl.Select(
                    csLine => new ResultLine
                    {
                        ProductName =csLine.Name,
                        Quantity = cl.Count().ToString(),
                        Price = cl.Sum(c …
Run Code Online (Sandbox Code Playgroud)

.net c# linq

112
推荐指数
3
解决办法
25万
查看次数

标签 统计

.net ×1

c# ×1

linq ×1