小编典典

Linq:GroupBy,求和和计数

c#

我有一个产品集合

public class Product {

   public Product() { }

   public string ProductCode {get; set;}
   public decimal Price {get; set; }
   public string Name {get; set;}
}

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

public class ResultLine{

   public ResultLine() { }

   public string ProductName {get; set;}
   public string Price {get; set; }
   public string Quantity {get; set;}
}

因此,我使用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 => c.Price).ToString(),
                    })).ToList<ResultLine>();

由于某种原因,总和正确完成,但计数始终为1。

Sampe数据:

List<CartLine> Lines = new List<CartLine>();
            Lines.Add(new CartLine() { ProductCode = "p1", Price = 6.5M, Name = "Product1" });
            Lines.Add(new CartLine() { ProductCode = "p1", Price = 6.5M, Name = "Product1" });
            Lines.Add(new CartLine() { ProductCode = "p2", Price = 12M, Name = "Product2" });

带有样本数据的结果:

Product1: count 1   - Price:13 (2x6.5)
Product2: count 1   - Price:12 (1x12)

产品1的计数应为2!

我试图在一个简单的控制台应用程序中对此进行仿真,但是得到了以下结果:

Product1: count 2   - Price:13 (2x6.5)
Product1: count 2   - Price:13 (2x6.5)
Product2: count 1   - Price:12 (1x12)

产品1:只应列出一次…以上代码可在pastebin上找到:http :
//pastebin.com/cNHTBSie


阅读 640

收藏
2020-05-19

共1个答案

小编典典

我不知道第一个“带有样本数据的结果”是从哪里来的,但是控制台应用程序中的问题是您正在SelectMany查看 每个组中的每个项目

我想您只想要:

List<ResultLine> result = Lines
    .GroupBy(l => l.ProductCode)
    .Select(cl => new ResultLine
            {
                ProductName = cl.First().Name,
                Quantity = cl.Count().ToString(),
                Price = cl.Sum(c => c.Price).ToString(),
            }).ToList();

使用First()此处获得产品名称的假设是,具有相同产品代码的每个产品都具有相同的产品名称。如注释中所述,您可以按产品名称和产品代码进行分组,如果名称对于任何给定代码始终相同,则将给出相同的结果,但是显然可以在EF中生成更好的SQL。

我还建议您分别将QuantityPrice属性分别更改为intdecimal类型-为什么要对明显不是文本的数据使用字符串属性?

2020-05-19