views:

412

answers:

2

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 and like C# ;)
+2  A: 

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

Russ C
This solution really works but have weak performance. When i insert/remove an element into/from the List, the sorted list will be ruined and because IList.Sort() it not "smart", i will have do more than a regular priority_queue
Isaac
In that case, don't use IList, but implement an ICollection and you can specify your own Insert method that lets you order correctly on insertion.
Russ C
@Ress C - 'ICollection' of 'List' class? Or using another class? can you provide a simple pseudocode? Thanks a lot!
Isaac
+3  A: 

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());
Lasse V. Karlsen
It seems that i have to save my element (the `Data` class) twice. As i said, i don't have a Key/Value pair. I have atomic elements from `Data` and a `Compare` function/class/...
Isaac
Shouldn't matter if the Data class is actually a class, it's only the reference you're storing twice. You could of course wrap that collection in one of your own, providing a leaner interface for your needs.
Lasse V. Karlsen
Thanks for the Snippet Lasse, got distracted by a manager :)
Russ C