【问题标题】:Extending A Custom Sort With A Custom Comparer使用自定义比较器扩展自定义排序
【发布时间】:2014-12-20 17:36:02
【问题描述】:

我有一个自定义排序,用于对列表进行排序,效果很好

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 添加到组合中,但在扩展方法时出现错误。

方法 'IOrderedEnumerable 的类型参数 System.Linq.Enumerable.OrderBy(这个 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)
    {
    }
}

【问题讨论】:

  • CustomComparer 的类型是什么?我的意思是它实现了 IComparer 还是 IEqualityComparer ?
  • 我用存根更新了问题

标签: c# linq


【解决方案1】:

OrderByDescending 方法中明确指定类型参数&lt;T, object&gt;

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();
    }

【讨论】:

  • 谢谢杰西,我认为视觉工作室搞砸了。我添加了 OrderByDecending 和 Resharper 表明它是多余的,所以我删除了它。在我删除它之后,VS 不再显示编译错误。很抱歉浪费您的时间,但它确实清除了我的错误。
猜你喜欢
  • 2013-11-04
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
相关资源
最近更新 更多