| 123456789101112131415161718192021222324252627282930313233343536373839 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Business.Core.Utilities
- {
- public class DynamicOrderComparer<T> : IComparer<T>
- {
- private readonly string[] _sortColumns;
- private readonly List<bool> _sortDirections; // true for ascending, false for descending
- public DynamicOrderComparer(string[] sortColumns, bool[] sortDirections)
- {
- _sortColumns = sortColumns;
- _sortDirections = sortDirections.ToList();
- }
- public int Compare(T x, T y)
- {
- for (int i = 0; i < _sortColumns.Length; i++)
- {
- var property = typeof(T).GetProperty(_sortColumns[i]);
- if (property == null) throw new ArgumentException($"Property {_sortColumns[i]} not found in type {typeof(T)}");
- var xValue = property.GetValue(x);
- var yValue = property.GetValue(y);
- if (xValue == null && yValue == null) return 0;
- if (xValue == null) return _sortDirections[i] ? -1 : 1;
- if (yValue == null) return _sortDirections[i] ? 1 : -1;
- var comparison = Comparer<object>.Default.Compare(xValue, yValue);
- if (comparison != 0) return _sortDirections[i] ? comparison : -comparison;
- }
- return 0;
- }
- }
- }
|