Sort objects in List by properties on the object

谁说胖子不能爱 提交于 2020-02-26 09:21:06

问题


I have a List of objects in C#. All the objects contain properties code1 and code2 (among other properties). The list of objects is in no particular order. I need to sort the list of objects by their code1 and code2 properties.

Example:

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

Example code 1 = 004
Example code 2 = 001, 002, 003, 004, 016
Example code 1 = 005
Example code 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

回答1:


You could use linq extensions (leaving the original list unsorted):

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<>().




回答2:


Note that Adam Houldsworth's answer with the .ToList() call needlessly creates a new list. If your list is large, this may create unacceptable memory pressure. It would most likely be better to sort the list in place by providing a custom comparison 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

theList.Sort();

... which will use the IComparable<T>.CompareTo() implementation.



来源:https://stackoverflow.com/questions/10013207/sort-objects-in-list-by-properties-on-the-object

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