用LINQ对类列表进行排序 [英] Sorting a List of Class with LINQ
本文介绍了用LINQ对类列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个List<MyClass>
,我想按MyClass的DateTime CreateDate
属性对其进行排序.
I have a List<MyClass>
and I want to sort it by DateTime CreateDate
attribute of MyClass.
使用LINQ可以吗?
谢谢
推荐答案
您可以按排序顺序枚举它:
You can enumerate it in sorted order:
IEnumerable<MyClass> result = list.OrderBy(element => element.CreateDate);
您还可以使用ToList()
转换为新列表并重新分配给原始变量:
You can also use ToList()
to convert to a new list and reassign to the original variable:
list = list.OrderBy(element => element.CreateDate).ToList();
这与对原始列表进行排序并不完全相同,因为如果仍然有人引用旧列表,他们将看不到新的排序.如果您实际上想对原始列表进行排序,则需要使用List<T>.Sort
方法.
This isn't quite the same as sorting the original list because if anyone still has a reference to the old list they won't see the new ordering. If you actually want to sort the original list then you need to use the List<T>.Sort
method.
这篇关于用LINQ对类列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文