how to sort List in c# / .net

前端 未结 4 1323
时光说笑
时光说笑 2021-01-11 10:25

I have a class PropertyDetails:

public class PropertyDetails
{

     public int Sequence { get; set; }

     public int Length { get; set; }

           


        
相关标签:
4条回答
  • 2021-01-11 10:49

    Using linq you can crate a new sorted list:

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

    If you want to sort your current list, you can use a comparer:

    list.Sort((details1, details2) => details1.Sequence.CompareTo(details2.Sequence);
    
    0 讨论(0)
  • 2021-01-11 10:53
    var sortedList = propertyDetailsList.OrderBy(pd => pd.Sequence);
    
    0 讨论(0)
  • 2021-01-11 10:56

    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<,>.

    0 讨论(0)
  • 2021-01-11 11:01

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

    0 讨论(0)
提交回复
热议问题