Search code examples
c#.netpriority-queue

Priority Queue in .Net


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 best 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

Solution

  • 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());