using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Reflection; using AntDesign.Internal; 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 Func _comparer; private SortDirection _sortDirection; private LambdaExpression _getFieldExpression; public SortModel(LambdaExpression getFieldExpression, string fieldName, int priority, SortDirection defaultSortOrder, Func comparer) { this.Priority = priority; this._getFieldExpression = getFieldExpression; this.FieldName = fieldName; 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 lambda = (Expression>)_getFieldExpression; 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; } } }