使用自定义比较器扩展自定义排序
本文关键字:自定义 排序 扩展 比较器 | 更新日期: 2023-09-27 18:34:57
我有一个自定义排序,我用它来对列表进行排序,效果很好
public static void Sort<T>(ref List<T> list, string propertyName, SortDirection direction)
{
var comparer = new CustomComparer();
list = direction == SortDirection.Ascending
? list.OrderBy(x => x.GetType().GetProperty(propertyName).GetValue(x, null)).ToList()
: list.OrderByDescending(x => x.GetType().GetProperty(propertyName).GetValue(x, null)).ToList();
}
现在我正在尝试将自定义比较器添加到组合中,但在扩展方法时出现错误。
方法"IOrderedEnumerable "的类型参数 System.Linq.Enumerable.OrderBy(this IEnumerable, Func, IComparer(' 不能是 从使用情况推断。尝试显式指定类型参数。
public static void Sort<T>(ref List<T> list, string propertyName, SortDirection direction)
{
list = direction == SortDirection.Ascending
? list.OrderBy(x => x.GetType().GetProperty(propertyName).GetValue(x, null), new CustomComparer()).ToList()
: list.OrderByDescending(x => x.GetType().GetProperty(propertyName).GetValue(x, null), new CustomComparer()).ToList();
}
我知道 OrderBy 设置不正确,有人有任何建议吗?
谢谢。
public class CustomComparer : IComparer<object>
{
public int Compare(object x, object y)
{
}
}
指定OrderByDescending
方法中显式<T, object>
的类型参数。
public class MyComparer : IComparer<object>
{
public int Compare(object x, object y)
{
throw new NotImplementedException();
}
}
public static void Sort<T>(ref List<T> list, string propertyName)
{
list = list.OrderByDescending<T, object>(x => x.GetType().GetProperty(propertyName).GetValue(x, null), new MyComparer()).ToList();
}