如何对List< T>进行排序在C#/.net中

如何对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.)