开发者

Priority Queue in .Net [duplicate]

This question already has answers here: Closed 9 years ago.

Possible Duplicate:

Priority queue in .Net

This question is similar, but i want to exactly know:

Is there any class/struct/... in .Net for priority queue? Just like in STL that have priority_queue for this. It accepts a comparsion function to support customized sorts.

The bes开发者_Go百科t thing i found in .Net is SortedList< Key, Value > that sorts it's values by Key. So one solution is implementing a custom Compare interface for Key class. But i cannot seperate my elements into Key/Value pairs. I have atomic elements that must queued according to their values with a custom function.

So, is there any collection class in .Net that accepts a Compare function for sorting the it's elements?

Is there any way to derive a .Net class (maybe HashSet) that supports this feature?


Note:

  • I know that many third-parties implemented really good classes for this. Maybe a good example is PowerCollections. But i want t quick and simple solution using existing classes in .Net
  • I am using .Net Framework 3.5


You can use a SortedDictionary class, which is generic.

You can specify a comparer object to the constructor, which should handle the priority comparison of your objects:

public class DataComparer : IComparer<Data>
{
    public Int32 Compare(Data a, Data b)
    {
        if (a == null && b == null)
            return 0;
        if (a == null)
            return -1;
        if (b == null)
            return +1;
        return a.Priority.CompareTo(b.Priority);
    }
}

SortedDictionary<Data, Data> priQueue = new SortedDictionary<Data, Data>(
    new DataComparer());


You could just implement IComparable on your class and create the specific comparer inside your class, that way you can just use IList.Sort() ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜