最佳答案
我有一系列的产品
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应该有计数 = 2!
我试图用一个简单的控制台应用模拟这个过程,但是我得到了以下结果:
Product1: count 2 - Price:13 (2x6.5)
Product1: count 2 - Price:13 (2x6.5)
Product2: count 1 - Price:12 (1x12)
产品1: 应该只列出一次..。 上述代码可以在 pastebin 上找到: < a href = “ http://pastebin.com/cnHTBsie”> http://pastebin.com/cnhtbsie