ฉันมีชุดผลิตภัณฑ์
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 data:
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