我正在将我的应用程序从 .Net 4.0 转换为 .Net 4.5 Framework,并且List<>
定义发生了变化。我的旧代码看起来像这样(.Net 4.0):
List<Customer> list = new List<Customer>();
list.Add(new Customer("Smith", "John", "Sydney", 45));
list.Add(new Customer("Mitchell", "Brad", "New York", 52));
list.Add(new Customer("Baker", "William", "Cape Town", 21));
list.OrderBy(x => x.Name);
使用 .Net 4.5 (C#5) 该List<T>.OrderBy()
方法消失了,只有List<T>.Sort()
可用,但看起来不可能在此方法中使用 Lambda 表达式。
IComparer
除了为每个定义一个之外,还有其他选择<T>
吗?如果真的没有 Lambda 表达式的选项,我可以使用 generic IComparer
,但是如何选择要比较的属性?
解决/编辑:
using Linq;
[...]
List<Customer> list = new List<Customer>();
list.Add(new Customer("Smith", "John", "Sydney", 45));
list.Add(new Customer("Mitchell", "Brad", "New York", 52));
list.Add(new Customer("Baker", "William", "Cape Town", 21));
list.OrderBy(x => x.Name); //list stays unordered
list = list.OrderBy(x => x.Name).ToList(); // list content is now ordered