Sorting a List of objects in C#

后端 未结 11 1885
终归单人心
终归单人心 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:21

    I would just use the build in List.Sort method. It uses the QuickSort algorithm which on average runs in O(n log n).

    This code should work for you, I change your properties to auto-properties, and defined a static CompareCarSpecs method that just uses the already existing DateTime.CompareTo method.

    class Program
    {
        static void Main(string[] args)
        {
            List cars = new List();
            cars.Sort(CarSpecs.CompareCarSpecs);
        }
    }
    
    public class CarSpecs
    {
        public string CarName { get; set; }
        public string CarMaker { get; set; }
        public DateTime CreationDate { get; set; }
    
        public static int CompareCarSpecs(CarSpecs x, CarSpecs y)
        {
            return x.CreationDate.CompareTo(y.CreationDate);
        }
    }
    

    Hope this helps.

提交回复
热议问题