fork download
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5.  
  6. public class Test
  7. {
  8. public class Stock
  9. {
  10. public int msft { get; set; }
  11. public string id { get; set; }
  12. public int price { get; set; }
  13. public int qty { get; set; }
  14. }
  15.  
  16.  
  17. public static void Main()
  18. {
  19. List<Stock> _investments = new List<Stock>()
  20. {
  21. new Stock {id="msft", price =12, qty=20},
  22. new Stock {id="msft", price =53, qty=50},
  23. new Stock {id="csco", price =222, qty=20},
  24. new Stock {id="fb", price =40, qty=100},
  25. };
  26.  
  27.  
  28. var result = _investments
  29. .GroupBy(i => i.id)
  30. .Where(g => g.Key == "msft")
  31. .Select(g => new{ id = g.Key, qty = g.Sum(i => i.qty), grp = g })
  32. .Select(x => new
  33. {
  34. x.id,
  35. x.qty,
  36. price = Math.Round(x.grp.Sum(i => (decimal)i.price * i.qty) / x.qty, 2)
  37. });
  38.  
  39. foreach(var x in result)
  40. Console.WriteLine("id={0} qty={1} price={2}",x.id,x.qty,x.price);
  41. }
  42. }
Success #stdin #stdout 0.05s 34112KB
stdin
Standard input is empty
stdout
id=msft qty=70 price=41.29