how to sort List<T> in c# / .net

。_饼干妹妹 提交于 2020-07-30 04:32:18

问题


I have a class PropertyDetails:

public class PropertyDetails
{

     public int Sequence { get; set; }

     public int Length { get; set; }

     public string Type { get; set; }
}

I am creating a list of PropertyDetails as

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

I want to sort this list by PropertyDetails.Sequence.

Linq solutions are welcome.


回答1:


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));

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

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




回答2:


Using linq you can use something similar to:

list.OrderBy(x => x.Sequence).toList();  

But I prefer to use a custom comparer.




回答3:


Don't ever use non-generic collections in C# when you can use generics instead. There are a lot of reasons to use generic collections only (except for very special cases).

See this question for more info: When would you not use Generic Collections?

So you can use List<PropertyDetails> (which I believe exposes a Sort() method) or SortedList<,>.




回答4:


var sortedList = propertyDetailsList.OrderBy(pd => pd.Sequence);


来源:https://stackoverflow.com/questions/4724027/how-to-sort-listt-in-c-sharp-net

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