简体   繁体   English

在 object 上按属性对 List 中的对象进行排序

[英]Sort objects in List by properties on the object

I have a List of objects in C#. All the objects contain properties code1 and code2 (among other properties).我在 C# 中有一个对象列表。所有对象都包含属性 code1 和 code2(以及其他属性)。 The list of objects is in no particular order.对象列表没有特定顺序。 I need to sort the list of objects by their code1 and code2 properties.我需要按对象的 code1 和 code2 属性对对象列表进行排序。

Example:例子:

List -> object = id, name, code1, code2, hours, amount.

Example code 1 = 004示例代码 1 = 004
Example code 2 = 001, 002, 003, 004, 016示例代码 2 = 001、002、003、004、016
Example code 1 = 005示例代码 1 = 005
Example code 2 = 001, 002, 003, 004示例代码 2 = 001、002、003、004

So after the sort I would want the objects in the following order所以在排序之后我希望对象按以下顺序排列

004 001
004 002
004 003
004 005
004 016
005 001
005 002
005 003
005 004

You could use linq extensions (leaving the original list unsorted):您可以使用 linq 扩展名(保留原始列表未排序):

var sorted = theList.OrderBy(o => o.code1).ThenBy(o => o.code2);

To replace the original list with a sorted one, make a slight amendment (not very efficient, it creates a new list):要用排序的列表替换原始列表,请稍作修改(效率不高,它会创建一个新列表):

theList = theList.OrderBy(o => o.code1).ThenBy(o => o.code2).ToList();

This assumes that your list is of the correct type, something like:这假定您的列表是正确的类型,例如:

List<MyClass> theList = new List<MyClass>();

And not a list of objects, in which case you would need to make use of .Cast<>() or .OfType<>() .而不是对象列表,在这种情况下,您需要使用.Cast<>().OfType<>()

Note that Adam Houldsworth's answer with the .ToList() call needlessly creates a new list.请注意,Adam Houldsworth 对.ToList()调用的回答不必要地创建了一个新列表。 If your list is large, this may create unacceptable memory pressure.如果您的列表很大,这可能会产生不可接受的 memory 压力。 It would most likely be better to sort the list in place by providing a custom comparison function:通过提供自定义比较 function 来对列表进行排序可能会更好:

theList.Sort((a, b) =>
    {
        var firstCompare = a.code1.CompareTo(b.code1);
        return firstCompare != 0 ? firstCompare : a.code2.CompareTo(b.code2);
    });

Alternatively, if this ordering is an intrinsic property of your type, you could implement IComparable<T> on your type, and just call或者,如果此顺序是您的类型的固有属性,您可以在您的类型上实现IComparable<T> ,然后调用

theList.Sort();

... which will use the IComparable<T>.CompareTo() implementation. ...这将使用IComparable<T>.CompareTo()实现。

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

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