Sorting a List of objects in C#

后端 未结 11 1863
终归单人心
终归单人心 2020-12-07 18:01
public class CarSpecs
{
  public String CarName { get; set; }

  public String CarMaker { get; set; }

  public DateTime CreationDate { get; set; }
}
相关标签:
11条回答
  • 2020-12-07 18:24

    I would avoid writing my own sorting algorithm, but if you are going to anyway, have a look at http://www.sorting-algorithms.com/ for some comparrisons of different sorting algorithms...

    0 讨论(0)
  • 2020-12-07 18:27

    If you're after an efficient way of sorting, I'd advise against using bubble sort and go for a quick sort instead. This page provides a rather good explanation of the algorithm:

    http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574

    Best of luck!

    0 讨论(0)
  • 2020-12-07 18:30

    You could use LINQ:

    listOfCars.OrderBy(x => x.CreationDate);
    

    EDIT: With this approach, its easy to add on more sort columns:

    listOfCars.OrderBy(x => x.CreationDate).ThenBy(x => x.Make).ThenBy(x => x.Whatever);
    
    0 讨论(0)
  • 2020-12-07 18:33

    The best approach is to implement either IComparable or IComparable<T>, and then call List<T>.Sort(). This will do all the hard work of sorting for you.

    0 讨论(0)
  • 2020-12-07 18:35

    The List<T> class makes this trivial for you, since it contains a Sort method. (It uses the QuickSort algorithm, not Bubble Sort, which is typically better anyway.) Even better, it has an overload that takes a Comparison<T> argument, which means you can pass a lambda expression and make things very simple indeed.

    Try this:

    CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));
    
    0 讨论(0)
提交回复
热议问题