c# - Linq:GroupBy、Sum 和 Count

标签 c# .net linq

我有一个产品系列

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。

样本数据:

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 应该有 count = 2!

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

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

Product1:应该只列出一次... 上面的代码可以在 pastebin 上找到:http://pastebin.com/cNHTBSie

最佳答案

我不明白第一个“样本数据结果”是从哪里来的,但控制台应用程序中的问题是您正在使用 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类型 - 为什么对显然不是文本的数据使用字符串属性?

关于c# - Linq:GroupBy、Sum 和 Count,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16522645/

相关文章:

java - 将 C# 代码移植到 Java

c# - 在 C# 中使用 'using' 指令的方法不那么乏味

c# - 在 WP7 项目中找不到 HttpWebRequest.GetResponse()

c# - Amazon S3 PutObject 非常慢

.net - 为什么 Convert.ToInt32 ("10.0") 失败

c# - Linq:将子集合向下排序 2 级

linq - 动态构建 Linq 查询

c# - 为 Windows 8 XAML 应用设置 UIElement 的位置

.net - 如何在 Windows 服务上捕获未处理的异常?

C# - 列表排序 - x 和 y