Hello colleagues. There are data on orders, who makes and how many days, pulled out the main fields is the name of the employee and the number of days to complete the order:

new OrderDetailsMini() { name = detailse.Employee.Name, days = detailse.Price.TimeCraft * detailse.Count }); 

There are a lot of such lines in the collection. How can I group people by name and calculate the sum of all the days they need for orders? Can this be done in LINQ or not? In SQL, this is easy, but something with EF I'm a little stuck.

  • Show in sql what you mean - Andrey NOP
  • one
    data.GroupBy(x => x.name, x=>x.days).Select(x => new OrderDetailsMini {name = x.Key, days = x.Sum()}) - tym32167
  • Thank you for what you need. I can see LINQ is still learning and teaching. :) - Chelios
  • @FoggyFinder Made answer - tym32167

2 answers 2

Use GroupBy to group data, GroupBy to summarize. Example:

 data .GroupBy(x => x.name, x=>x.days) .Select(x => new OrderDetailsMini {name = x.Key, days = x.Sum()}) 
  • And why in .GroupBy (x = x.days)? We on it cause aggregate? - Roman Ieromenko
  • @RomanIeromenko Take a closer look, there is a grouping for the name, for the days just a selector - tym32167
  • But we need a sum of days, grouped by name - Roman Ieromenko
  • this code .GroupBy(x => x.name, x=>x.days) will create groups, where in each group the key will be the name and the set of values ​​will be the days for that name. Therefore, further, in the selector, I can transform each group into 1 record, writing out the key (which is the name) from it and summing up the days, as required - tym32167

I dare to correct

  static void Main(string[] args) { List<OrderDetailsMini> datal; datal = new List<OrderDetailsMini>(); datal.Add(new OrderDetailsMini("Ваня", 15)); datal.Add(new OrderDetailsMini("Ваcя", 25)); datal.Add(new OrderDetailsMini("Егор", 5)); datal.Add(new OrderDetailsMini("Ваня", 15)); datal.Add(new OrderDetailsMini("Вера", 8)); datal.Add(new OrderDetailsMini("Егор", 21)); var spor = datal.GroupBy(x => x.name, x => x.days).Select(x=> new OrderDetailsMini (x.Key, x.Sum())).ToArray(); foreach (var item in spor) { Console.WriteLine("Name :{0}, days total :{1}",item.name, item.days); } } class OrderDetailsMini { public string name; public int days; public OrderDetailsMini(string name, int days) { this.name = name; this.days = days; } } 

Result in the image enter image description here