Linq: GroupBy, Sum and Count

后端 未结 3 2231
庸人自扰
庸人自扰 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

    sometimes you need to select some fields by FirstOrDefault() or singleOrDefault() you can use the below query:

    List result = Lines
        .GroupBy(l => l.ProductCode)
        .Select(cl => new Models.ResultLine
                {
                    ProductName = cl.select(x=>x.Name).FirstOrDefault(),
                    Quantity = cl.Count().ToString(),
                    Price = cl.Sum(c => c.Price).ToString(),
                }).ToList();
    

提交回复
热议问题