DynamicGridDurationAggregate.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Linq;
  7. using InABox.Core;
  8. using InABox.WPF;
  9. namespace InABox.DynamicGrid;
  10. public class DynamicGridDurationAggregate : IDynamicGridSummaryAggregate
  11. {
  12. public int Count { get; private set; }
  13. public TimeSpan Sum { get; private set; }
  14. public Action<IEnumerable, string, PropertyDescriptor> CalculateAggregateFunc()
  15. {
  16. return CalculateAggregate;
  17. }
  18. private void CalculateAggregate(IEnumerable items, string property, PropertyDescriptor args)
  19. {
  20. if (items is IEnumerable<DataRowView> rows)
  21. {
  22. if (string.Equals(args.Name, "Count"))
  23. {
  24. Count = rows.Count();
  25. }
  26. else if (string.Equals(args.Name, "Sum"))
  27. {
  28. Sum = new TimeSpan();
  29. foreach (var row in rows)
  30. if (row[property] is TimeSpan)
  31. Sum += (TimeSpan)row[property];
  32. }
  33. }
  34. else
  35. {
  36. Logger.Send(LogType.Error, "", $"Attempting to calculate aggregate on invalid data type '{items.GetType()}'.");
  37. }
  38. }
  39. public string Format(String command, String format)
  40. {
  41. if (string.Equals(command, "Sum"))
  42. return string.IsNullOrWhiteSpace(format) || string.Equals(format, "hh':'mm")
  43. ? Math.Truncate(Sum.TotalHours).ToString("#00") + ":" + Sum.Minutes.ToString("D2")
  44. : new TimeSpanToStringConverter(format).Convert(Sum);
  45. if (string.Equals(command, "Count"))
  46. return string.Format(format, Count);
  47. return "";
  48. }
  49. }