如何对List< T>进行排序在C#中 [英] How to sort List<T> in c#
问题描述
我有一个List<Card>
,我想对这些卡片进行排序
I've got a List<Card>
, and I want to sort these cards
因此,我正在寻找一种方法,可以根据不同的条件对它们进行排序,例如其ID
,其Name
...
So, I'm looking for a method to sort them with different criterias, like their ID
, their 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向我发送了一个错误消息:
But then, visual studio sent me an error :
'Card'
未实现接口成员'IComparer<Card>.Compare(Card, Card)'
'Card'
does not implement interface member'IComparer<Card>.Compare(Card, Card)'
推荐答案
您可能希望拥有自己的课程 比较器
You, probably, want to have your class Comparable not a 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();
编辑:如果要选择多个条件,则必须将多个比较器实现为单独的类,例如
If you want to have several criteria to choose from, you have to implement several Comparers as separated classes, e.g.
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);
}
}
,并在排序时提供所需的内容:
and when sorting provide the required:
List<Card> myList = ...
myList.Sort(new CardByIdComparer());
(受支出者图书馆的启发).如果要组合多个比较器成一个(即,使用comparer1
,平局-comparer2
等)
Edit 2: (inspired by spender's library). If you want to combine several comparers into one (i.e. use comparer1
, on tie - comparer2
etc.)
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>进行排序在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!