Linq: GroupBy, Sum and Count

后端 未结 3 2131
庸人自扰
庸人自扰 2020-11-22 15:45

I have a collection of products

public class Product {

   public Product() { }

   public string ProductCode {get; set;}
   public decimal Price {get; set;          


        
3条回答
  •  无人及你
    2020-11-22 16:02

    The following query works. It uses each group to do the select instead of SelectMany. SelectMany works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping in the select portion to get your aggregate operations working correctly.

    var results = from line in Lines
                  group line by line.ProductCode into g
                  select new ResultLine {
                    ProductName = g.First().Name,
                    Price = g.Sum(pc => pc.Price).ToString(),
                    Quantity = g.Count().ToString(),
                  };
    

提交回复
热议问题