如何在 C# 中对 List<T> 进行排序

我有一个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)'


江户川乱折腾
浏览 139回答 4
4回答

噜噜哒

您可能希望让您的类成为Comparable而不是Comparatorpublic 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, on 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));

慕斯709654

最简单的方法你可以使用 Linq:List<Card>&nbsp;objSortedList&nbsp;=&nbsp;objListObject.OrderBy(o=>o.ID).ToList();或者List<Card>&nbsp;objSortedList&nbsp;=&nbsp;objListObject.OrderByDescending(o=>o.ID).ToList();

不负相思意

您需要实现 IComparerpublic int Compare(Card card1, Card card2){&nbsp; &nbsp;if (card1.ID > card2.ID)&nbsp; &nbsp; &nbsp; return 1; //move card1 up&nbsp; &nbsp;if (card2.ID&nbsp; < card1.ID)&nbsp; &nbsp; &nbsp; return -1; //move card2 up&nbsp; return 0; //do nothing}

慕丝7291255

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++;         }     } } 
打开App,查看更多内容
随时随地看视频慕课网APP