我有一个自定义排序,我用它来排序一个工作正常的列表
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();
}
现在我尝试在混合中添加CustomComparer,并在扩展方法时出错。
方法&#39; IOrderedEnumerable的类型参数 System.Linq.Enumerable.OrderBy(此 IEnumerable,Func,IComparer)&#39;不可能是 从用法推断。尝试明确指定类型参数。
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();
}
我知道订单设置不正确有人有任何建议吗?
感谢。
public class CustomComparer : IComparer<object>
{
public int Compare(object x, object y)
{
}
}
答案 0 :(得分:1)
在<T, object>
方法中明确指定类型参数OrderByDescending
。
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();
}