Sorting a List of objects in C#

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

    Another option would be to use a custom comparer:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Yournamespace
    {
       class CarNameComparer : IComparer
       {
          #region IComparer Members
    
          public int Compare(Car car1, Car car2)
          {
             int returnValue = 1;
             if (car1 != null && car2 == null)
             {
                returnValue = 0;
             }
             else if (car1 == null && car2 != null)
             {
                returnValue = 0;
             }
             else if (car1 != null && car2 != null)
             {
                if (car1.CreationDate.Equals(car2.CreationDate))
                {
                   returnValue = car1.Name.CompareTo(car2.Name);
                }
                else
                {
                   returnValue = car2.CreationDate.CompareTo(car1.CreationDate);
                }
             }
             return returnValue;
          }
    
          #endregion
       }
    }
    

    which you call like this:

    yourCarlist.Sort(new CarNameComparer());
    

    Note: I didn't compile this code so you might have to remove typo's

    Edit: modified it so the comparer compares on creationdate as requested in question.

提交回复
热议问题