製品のコレクションがあります
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:上記のコードはペーストビン上で見つけることができたら...のみ表示される必要がありhttp://pastebin.com/cNHTBSie