Linq:GroupBy,Sum和Count
我有一系列产品
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应该有count = 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
当年话下
青春有我
侃侃无极
随时随地看视频慕课网APP