views:

130

answers:

3

I have a collection of objects and I know that I can sort by NAME (string type) by saying

collEquipment.Sort((x, y) => string.Compare(x.ItemName, y.ItemName));

that WORKS.

But I want to sort by a ID (integer type) and there is no such thing as Int32.Compare

So how do I do this? This doesn't work

collEquipment.Sort((x, y) => (x.ID < y.ID));  //error

I know the answer is going to be really simple. Lambda expressions confuse me.

+3  A: 

try this

collEquipment.Sort((x, y) => y.ID - x.ID);
SysAdmin
possibly has some wrap-around issues with very large numbers
Marc Gravell
great works thanks! its just IDs for items in a DB.. so won't be too large
punkouter
@Marc Gravell - I guess this would be the same case for any method right?
SysAdmin
You shouldn't use `-` to implement CompareTo - it does not work (overflow problems etc.)
BlueRaja - Danny Pflughoeft
Still don't get how "y.ID - x.ID" = "Sort these integers"Have to study more.
punkouter
@punkouter: He is using subtraction to implement CompareTo, which is flawed. See [this post](http://stackoverflow.com/questions/2728793/java-integer-what-is-faster-comparison-or-subtraction).
BlueRaja - Danny Pflughoeft
@punkouter: The sort func needs to return a 0, >0, or a <0 result. Subtracting the compare values will do that (more or less), but it would be better to use the Int32.CompareTo() method. So replace y.ID - x.ID with y.ID.CompareTo(x.ID), as JWL_ pointed out below.
code4life
+6  A: 
collEquipment.Sort((x, y) => y.ID.CompareTo(x.ID));
JWL_
+2  A: 

Here you go, sort a list against any property that implements IComparable[<T>] (which int does):

public static class ListExtensions {
    public static void Sort<TSource, TValue>(
        this List<TSource> list,
        Func<TSource, TValue> selector) {
        list.Sort((x,y) => Comparer<TValue>.Default
            .Compare(selector(x),selector(y)));
    }
}

Now:

collEquipment.Sort(x => x.ItemName);

or

collEquipment.Sort(x => x.ID);
Marc Gravell