简体   繁体   English

如何使用Lambda表达式对对象内的INTEGERS进行排序?

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

I have a collection of objects and I know that I can sort by NAME (string type) by saying 我有一个对象的集合,我知道我可以按照NAME(字符串类型)排序

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 但我想按ID(整数类型)排序,并且没有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. Lambda的表达让我很困惑。

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): 在这里,您可以针对实现IComparable[<T>]任何属性(对于int执行此操作)对列表进行排序:

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

尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM