如何对List< T>进行排序在C#/.net中 [英] how to sort List<T> in c# / .net

查看:45
本文介绍了如何对List< T>进行排序在C#/.net中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 PropertyDetails :

public class PropertyDetails
{

     public int Sequence { get; set; }

     public int Length { get; set; }

     public string Type { get; set; }
}

我正在创建

List<PropertyDetails> propertyDetailsList=new List<PropertyDetails>();

我想按 PropertyDetails.Sequence 对此列表进行排序.

I want to sort this list by PropertyDetails.Sequence.

欢迎使用Linq解决方案.

Linq solutions are welcome.

推荐答案

如果要就地对现有列表进行排序,则可以使用

If you want to sort the existing list in-place then you can use the Sort method:

List<PropertyDetails> propertyDetailsList = ...
propertyDetailsList.Sort((x, y) => x.Sequence.CompareTo(y.Sequence));

如果要创建列表的新的排序副本,则可以使用LINQ的

If you want to create a new, sorted copy of the list then you can use LINQ's OrderBy method:

List<PropertyDetails> propertyDetailsList = ...
var sorted = propertyDetailsList.OrderBy(x => x.Sequence).ToList();

(如果您不需要结果作为具体的 List< T> ,则可以省略最后的 ToList 调用.)

(And if you don't need the results as a concrete List<T> then you can omit the final ToList call.)

这篇关于如何对List&lt; T&gt;进行排序在C#/.net中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆