using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Business.Core.Utilities { public class DynamicOrderComparer : IComparer { private readonly string[] _sortColumns; private readonly List _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.Default.Compare(xValue, yValue); if (comparison != 0) return _sortDirections[i] ? comparison : -comparison; } return 0; } } }