C# - IComparer - If datetime is null then should be sorted to the bottom not the top

前端 未结 3 1707
旧时难觅i
旧时难觅i 2021-02-09 08:29

I have a list of dates that I want to sort in an ascending order. However, the default comparer means that I have:

null
null
18/01/2011
23/01/2011
3条回答
  •  萌比男神i
    2021-02-09 08:40

    public class DateTimeComparer : IComparer
    {
        #region IComparer Members
    
        public int Compare(DateTime? x, DateTime? y)
        {
            DateTime nx = x ?? DateTime.MaxValue;
            DateTime ny = y ?? DateTime.MaxValue;
    
            return nx.CompareTo(ny);
        }
    
        #endregion
    }
    

    No extra null checking is required.

提交回复
热议问题