答案 0 :(得分:3)
您可以使用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>
。如果添加多个比较相等的对象,它们将被丢弃。
答案 1 :(得分:2)
您需要PriorityQueue
。您可以在这个类似的问题中找到几个实现:C# Priority Queue。
答案 2 :(得分:1)
C5 has an IntervalHeap做我想做的事。