fork(1) download
  1. using System; using System.Linq; using System.Collections.Generic;
  2.  
  3. public class Test
  4. {
  5. public static void Main()
  6. {
  7. var Products = new List<Product>
  8. {
  9. new Product { Name = "XXXVVVXXXX", Category = "Category1", Price = 10 },
  10. new Product { Name = "YYYY", Category = "Category2", Price = 5 },
  11. new Product { Name = "XXYZXXXXXX", Category = "Category1", Price = 15 },
  12. new Product { Name = "YYVV", Category = "Category2", Price = 10 },
  13. new Product { Name = "TTTT", Category = "Category2", Price = 11 }
  14. };
  15.  
  16. var query =
  17. from p in Products
  18. group p by p.Category into g
  19. select new { Category = g.Key, Total = g.Sum(p => p.Price), Values = g };
  20.  
  21. foreach (var g in query) {
  22. foreach (Product p in g.Values) {
  23. Console.WriteLine("{0}\t|\t{1}\t|\t{2}", p.Name, p.Category, p.Price);
  24. }
  25. Console.WriteLine("Total {0}:\t{1}", g.Category, g.Total);
  26. }
  27.  
  28. }
  29. }
  30.  
  31. class Product
  32. {
  33. public string Name { get; set; }
  34. public string Category { get; set; }
  35. public int Price { get; set; }
  36. }
  37.  
Success #stdin #stdout 0.04s 34072KB
stdin
Standard input is empty
stdout
XXXVVVXXXX	|	Category1	|	10
XXYZXXXXXX	|	Category1	|	15
Total Category1:	25
YYYY	|	Category2	|	5
YYVV	|	Category2	|	10
TTTT	|	Category2	|	11
Total Category2:	26