开发者

How do I use a Lambda expression to sort INTEGERS inside a object?

开发者 https://www.devze.com 2022-12-29 06:58 出处:网络
I have a collection of objects and I know that I can sort by NAME (string type)开发者_StackOverflow by saying

I have a collection of objects and I know that I can sort by NAME (string type)开发者_StackOverflow 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.


collEquipment.Sort((x, y) => y.ID.CompareTo(x.ID));


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


try this

collEquipment.Sort((x, y) => y.ID - x.ID);
0

精彩评论

暂无评论...
验证码 换一张
取 消