How to sort a List collection of classes with properties in them?

前端 未结 3 374
误落风尘
误落风尘 2020-12-16 03:30

I have a List of classes in my collection like

List test = new List();

In my classes I have just some propert

相关标签:
3条回答
  • 2020-12-16 03:53

    How about:

    list.Sort((x,y) => DateTime.Compare(x.date, y.date));
    

    which sorts the existing list, or:

    var sorted = list.OrderBy(x=>x.date).ToList();
    

    which creates a second list.

    0 讨论(0)
  • 2020-12-16 04:11

    Once you have your classes in your list, and the list is complete:

    List<MyClass> testList = new List<MyClass>();
    // populate the list...
    
    var orderedList = testList.OrderBy( x => x.date ).ToList();
    
    0 讨论(0)
  • 2020-12-16 04:13

    If you want to sort them in place, you can use List<T>.Sort:

    test.Sort( (l,r) => l.date.CompareTo(r.date) );
    

    If you want to sort them into a new result set, LINQ is very nice:

    var sortedResults = from mc in test
                        order by mc.date
                        select mc;
    
    0 讨论(0)
提交回复
热议问题