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

时间:2019-08-06 07:59:29

标签: c# list sorting

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

4 个答案:

答案 0 :(得分:22)

您可能想让您的课程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,平局-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
));

答案 1 :(得分:13)

使用Linq的最简单方法:

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

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

答案 2 :(得分:1)

Good examples for演示了
的概念 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++; 
        } 

    } 


} 

答案 3 :(得分:0)

您需要实现IComparer

public int Compare(Card card1, Card card2)
{
   if (card1.ID > card2.ID)
      return 1; //move card1 up
   if (card2.ID  < card1.ID)
      return -1; //move card2 up
  return 0; //do nothing
}