最佳答案
您可以使用 SortedSet<T>
,这是 .NET 4 中的新增功能。您可以在实现 IComparable<T>
的类上使用它。或者您可以通过构造函数重载提供外部比较器。示例:
class Foo
{
public int Bar { get; set; }
}
class FooComparer : IComparer<Foo>
{
public int Compare(Foo x, Foo y)
{
// add null checking, demo purposes only
return x.Bar.CompareTo(y.Bar);
}
}
...
SortedSet<Foo> sortedFoos = new SortedSet<Foo>(new FooComparer());
sortedFoos.Add(new Foo() { Bar = 2 });
sortedFoos.Add(new Foo() { Bar = 1 });
foreach (Foo foo in sortedFoos)
{
Console.WriteLine(foo.Bar);
}
// Prints 1, 2
注意:此集合的行为类似于 HashSet<T>
。如果添加多个比较相等的对象,它们将被丢弃。
关于c# - 根据特定属性维护排序顺序的集合类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4576616/