code_junkie

LINQ query with multiple aggregates

Nov 11th, 2011
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn,
  2. MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt
  3. FROM Punches p
  4.  
  5. List<int> myInts = new List<int>() { 1, 4, 2, 0, 3 };
  6. var y = myInts.Aggregate(
  7. new { Min = int.MaxValue, Max = int.MinValue },
  8. (a, i) =>
  9. new
  10. {
  11. Min = (i < a.Min) ? i : a.Min,
  12. Max = (a.Max < i) ? i : a.Max
  13. });
  14. Console.WriteLine("{0} {1}", y.Min, y.Max);
  15.  
  16. var times = punches.Aggregate(
  17. new { EarliestIn = default(DateTime?), LatestOut = default(DateTime?) },
  18. (agg, p) => new {
  19. EarliestIn = Min(
  20. agg.EarliestIn,
  21. p.type == "In" ? (DateTime?)p.PunchTime : default(DateTime?)),
  22. LatestOut = Max(
  23. agg.LatestOut,
  24. p.type == "Out" ? (DateTime?)p.PunchTime : default(DateTime?))
  25. }
  26. );
  27.  
  28. public static DateTime? Max(DateTime? d1, DateTime? d2)
  29. {
  30. if (!d1.HasValue)
  31. return d2;
  32. if (!d2.HasValue)
  33. return d1;
  34. return d1.Value > d2.Value ? d1 : d2;
  35. }
  36. public static DateTime? Min(DateTime? d1, DateTime? d2)
  37. {
  38. if (!d1.HasValue)
  39. return d2;
  40. if (!d2.HasValue)
  41. return d1;
  42. return d1.Value < d2.Value ? d1 : d2;
  43. }
Add Comment
Please, Sign In to add comment