簡體   English   中英

使用自定義比較器擴展自定義排序

[英]Extending A Custom Sort With A Custom Comparer

我有一個自定義排序,用於對列表進行排序,效果很好

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)
    {
    }
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM