views:

125

answers:

5

I have a List where element is:

struct element { 
                double priority; 
                int value; 
               }

How can I implement my own comparer which allow me sort List by priority ? I try with SortredList... but it don't allow douplicated keys :(

Big thanks for help!

+11  A: 

Assuming C# 3 or later:

var sorted = MyList.OrderBy(e => e.priority);
Joel Coehoorn
Worth pointing out that this will return a new `IEnumerable<>` rather than sorting the existing `List<>` in-place.
LukeH
Note that this won't sort the list, it will return an ordered list element by element when iterated over.
Blindy
I am more think about Sort method which manipulate collection and save result. But Tnx for this also! I am appreciated Your help :)
netmajor
A: 

If you want to sort the list itself without creating a new instance, you can implement IComparer, then call List.Sort with an instance of your implementation

public class ElementComparer : IComparer<element>
{
    public int Compare(element x, element y)
    {
        throw new NotImplementedException();
    }
}
Bubblewrap
...with `throw new NotImplementedException();` replaced with `return x.priority.CompareTo(y.priority);`! :)
gehho
Without gehho comment Your answer is partial ..
netmajor
+8  A: 

You can perform an in-place sort by using the Sort overload that takes a Comparison<T> delegate:

yourList.Sort((x, y) => x.priority.CompareTo(y.priority));

For older versions of C# you'll need to swap out the lambda for old-school delegate syntax:

yourList.Sort(
    delegate(element x, element y) { return x.priority.CompareTo(y.priority); });
LukeH
I am appreciated this two-school way sort example!
netmajor
I cannot get the lamda suggestion to work? I am using 3.5, it says cannot resolve symbol CompareTo
Lucifer
Lucifer: probably due to `priority` being a private member of the `element` struct
Isak Savo
+3  A: 

If you can't rely on C# 3 extensions or Lambdas then you can have your struct implement the IComparable interface, like so:

struct element : IComparable
{
    double priority;
    int value;
    public element(int val, double prio)
    {
        priority = prio;
        value = val;
    }
    #region IComparable Members

    public int CompareTo(object obj)
    {
        // throws exception if type is wrong
        element other = (element)obj;
        return priority.CompareTo(other.priority);
    }

    #endregion
}

There are also a typesafe version of this interface, but the principle is the same

After you have that interface implemented on your struct or class, calling the Sort method on List<> will "just work"

static void Main(string[] args)
{
    Random r = new Random();
    List<element> myList = new List<element>();
    for (int i = 0; i < 10; i++)
        myList.Add(new element(r.Next(), r.NextDouble()));
    // List is now unsorted 
    myList.Sort();
    // List is now sorted by priority
    Console.ReadLine();
}
Isak Savo
Even in 2.0 you can use the anonymous method approach, though.
Marc Gravell
Great implementation! Thanks for use example ;) This is what I need! :)
netmajor
Marc: yeah you are correct. One benefit of this approach though is that it works automatically for all places where someone needs to sort a collection of `element`s.
Isak Savo
+1  A: 

This depends on if you want to sort the list itself, or retrieve the values in sorted order (without changing the list).

To sort the list itself (supposing you have a List<element> called elements):

elements.Sort((x, y) => x.priority.CompareTo(y.priority));
// now elements is sorted

.NET 2.0 equivalent:

elements.Sort(
    delegate(element x, element y) {
        return x.priority.CompareTo(y.priority);
    }
);

To get the values in sorted order:

var orderedElements = elements.OrderBy(x => x.priority);
// elements remains the same, but orderedElements will retrieve them in order

There's no LINQ equivalent in .NET 2.0, but you can write your own:

public static IEnumerable<T> OrderBy<T>(IEnumerable<T> source, Comparison<T> comparison) {
    List<T> copy = new List<T>(source);
    copy.Sort(comparison);

    foreach (T item in copy)
        yield return item;
}

Usage:

Comparison<element> compareByPriority = delegate(element x, element y) {
    return x.priority.CompareTo(y.priority);
};

// unfortunately .NET 2.0 doesn't support extension methods, so this has to be
// expressed as a regular static method
IEnumerable<element> orderedElements = OrderBy(elements, compareByPriority);
Dan Tao
Nice compilation of all answers :P
netmajor