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.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
punkouter
  • 5,170
  • 15
  • 71
  • 116

3 Answers3

16
collEquipment.Sort((x, y) => y.ID.CompareTo(x.ID));
JWL_
  • 829
  • 5
  • 15
  • 1
    The short explanation of *why* this works is that Sort does not take a less-than operator - it takes a "comparator" operator which returns <0 if x0 if x>y, or 0 if x==y. So it always expects an integer result, not a boolean. The CompareTo() method on int returns <0, 0, or >0 in this pattern, so you can use it to solve your problem succinctly, although using if-else would work as well (if (x.IDy.ID) return 1; else return 0;). – Chiara Coetzee Oct 06 '12 at 03:30
8

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
  • 1,026,079
  • 266
  • 2,566
  • 2,900
7

try this

collEquipment.Sort((x, y) => y.ID - x.ID);
SysAdmin
  • 5,455
  • 8
  • 33
  • 34