根据特定属性维护排序顺序的集合类?

时间:2011-01-02 01:07:27

标签: c# data-structures

我正在寻找一个集合类,它将根据属性(即“优先级”)自动按排序顺序插入元素,这样当我稍后迭代它时,我将按此顺序返回元素。


SortedList似乎按键排序,这不是我想要的。

3 个答案:

答案 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做我想做的事。