DynamicOrderComparer.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Business.Core.Utilities
  7. {
  8. public class DynamicOrderComparer<T> : IComparer<T>
  9. {
  10. private readonly string[] _sortColumns;
  11. private readonly List<bool> _sortDirections; // true for ascending, false for descending
  12. public DynamicOrderComparer(string[] sortColumns, bool[] sortDirections)
  13. {
  14. _sortColumns = sortColumns;
  15. _sortDirections = sortDirections.ToList();
  16. }
  17. public int Compare(T x, T y)
  18. {
  19. for (int i = 0; i < _sortColumns.Length; i++)
  20. {
  21. var property = typeof(T).GetProperty(_sortColumns[i]);
  22. if (property == null) throw new ArgumentException($"Property {_sortColumns[i]} not found in type {typeof(T)}");
  23. var xValue = property.GetValue(x);
  24. var yValue = property.GetValue(y);
  25. if (xValue == null && yValue == null) return 0;
  26. if (xValue == null) return _sortDirections[i] ? -1 : 1;
  27. if (yValue == null) return _sortDirections[i] ? 1 : -1;
  28. var comparison = Comparer<object>.Default.Compare(xValue, yValue);
  29. if (comparison != 0) return _sortDirections[i] ? comparison : -comparison;
  30. }
  31. return 0;
  32. }
  33. }
  34. }