如何在C#中對List<T>進行排序




sorting (3)

我有一個 List<Card> ,我想對這些卡進行排序

因此,我正在尋找一種使用不同條件對它們進行排序的方法,例如其 ID ,其 Name ...

public class Card : IComparer
{
    public string ID;
    public string Name;
    public int CompareId(object firstCard, object secondCard) 
    {
        Card c1 = (Card)firstCard;
        Card c2 = (Card)secondCard;
        return c1.Id.CompareTo(c2.Id);
    }
}

但是隨後,Visual Studio向我發送了一個錯誤:

'Card' 未實現接口成員 'IComparer<Card>.Compare(Card, Card)'


您可以使用Linq的最簡單方法:

List<Card> objSortedList = objListObject.OrderBy(o=>o.ID).ToList();

要么

List<Card> objSortedList = objListObject.OrderByDescending(o=>o.ID).ToList();

您可能希望讓您的班級 Comparable 而不是 Comparator

public class Card : IComparable<Card>
{
    public string ID;
    public string Name;

    public int CompareTo(Card other) 
    {
        if (null == other)
            return 1;

        // string.Compare is safe when Id is null 
        return string.Compare(this.Id, other.Id);
    }
}

然後

List<Card> myList = ...

myList.Sort();

編輯: 如果要選擇 多個 條件,則必須將多個比較器實現為單獨的類,例如

public sealed class CardByIdComparer : IComparer<Card> 
{
    public int Compare(Card x, Card y) 
    {
        if (object.ReferenceEquals(x, y))
            return 0;
        else if (null == x)
            return -1;
        else if (null == y)
            return 1;
        else
            return string.Compare(x.Id, y.Id);
    }
}

並在排序時提供所需的信息:

List<Card> myList = ...

myList.Sort(new CardByIdComparer());

編輯2 :( 受支出者圖書館的啟發)。 如果要將多個比較器 組合 為一個(例如,使用 comparer1 ,在tie- comparer2 上等)

public sealed class ComparerCombined<T> : IComparer<T> {
  private IComparer<T>[] m_Comparers;

  public ComparerCombined(params IComparer<T>[] comparers) {
    if (null == comparers)
      throw new ArgumentNullException(nameof(comparers));

    m_Comparers = comparers
      .Select(item => item == null ? Comparer<T>.Default : item)
      .Where(item => item != null)
      .Distinct()
      .ToArray();
  }

  public int Compare(T x, T y) {
    if (object.ReferenceEquals(x, y))
      return 0;
    else if (null == x)
      return -1;
    else if (null == y)
      return 1;

    foreach (var comparer in m_Comparers) {
      int result = comparer.Compare(x, y);

      if (result != 0)
        return result;
    }

    return 0;
  }
}

用法:

myList.Sort(new ComparerCombined(
  new CardByIdComparer(),   // Sort By Id
  new CardByNameComparer()  // On tie (equal Id's) sort by name
));

很好的例子來 說明
List<T>.Sort(IComparer <T>) 方法請檢查鏈接。

在此示例中, IComparer<T> 比較用於字符串 IComparer<T> 但是您也可以將其用於ID(int)。

using System; 
using System.Collections.Generic; 

class GFG : IComparer<string> 
{ 
    public int Compare(string x, string y) 
    { 
        if (x == null || y == null) 
        { 
            return 0; 
        } 

        // "CompareTo()" method 
        return x.CompareTo(y); 

    } 
} 



public class geek 
{ 
    public static void Main() 
    { 
        List<string> list1 = new List<string>(); 

        // list elements 
        list1.Add("C++"); 
        list1.Add("Java"); 
        list1.Add("C"); 
        list1.Add("Python"); 
        list1.Add("HTML"); 
        list1.Add("CSS"); 
        list1.Add("Scala"); 
        list1.Add("Ruby"); 
        list1.Add("Perl"); 

        int range = 4; 

        GFG gg = new GFG(); 

        Console.WriteLine("\nSort a range with comparer:"); 

        // sort the list within a  
        // range of index 1 to 4 
        // where range = 4 
        list1.Sort(1, range, gg); 

        Console.WriteLine("\nBinarySearch and Insert Dart"); 

        // Binary Search and storing  
        // index value to "index" 
        int index = list1.BinarySearch(0, range, 
                                    "Dart", gg); 

        if (index < 0) 
        { 
            list1.Insert(~index, "Dart"); 
            range++; 
        } 

    } 


} 




sorting