using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace AntDesign.TableModels { public class SortModel : ITableSortModel, IComparer { public int Priority { get; } public string FieldName { get; } public string Sort => _sortDirection?.Name; SortDirection ITableSortModel.SortDirection => _sortDirection; private readonly PropertyInfo _propertyInfo; private readonly Func _comparer; private SortDirection _sortDirection; public SortModel(PropertyInfo propertyInfo, int priority, SortDirection defaultSortOrder, Func comparer) { this.Priority = priority; this.FieldName = propertyInfo?.Name; this._propertyInfo = propertyInfo; this._comparer = comparer; this._sortDirection = defaultSortOrder ?? SortDirection.None; } void ITableSortModel.SetSortDirection(SortDirection sortDirection) { _sortDirection = sortDirection; } IOrderedQueryable ITableSortModel.SortList(IQueryable source) { if (_sortDirection == SortDirection.None) { return source as IOrderedQueryable; } var sourceExpression = Expression.Parameter(typeof(TItem)); var propertyExpression = Expression.Property(sourceExpression, _propertyInfo); var lambda = Expression.Lambda>(propertyExpression, sourceExpression); if (_sortDirection == SortDirection.Ascending) { return _comparer == null ? source.OrderBy(lambda) : source.OrderBy(lambda, this); } else { return _comparer == null ? source.OrderByDescending(lambda) : source.OrderByDescending(lambda, this); } } /// public int Compare(TField x, TField y) { return _comparer?.Invoke(x, y) ?? 0; } } }