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

只谈情不闲聊 提交于 2019-12-24 05:38:15

问题


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.


回答1:


try this

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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/2766686/how-do-i-use-a-lambda-expression-to-sort-integers-inside-a-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!