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

前端 未结 3 1640
旧时难觅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条回答
  •  北荒
    北荒 (楼主)
    2021-02-09 08:50

    Here's a generic comparer that should work for pretty much any type:

    var yourList = new List
                       {
                           null, new DateTime(2011, 1, 23),
                           null, new DateTime(2011, 1, 18)
                       };
    
    var comparer = new NullsLastComparer();
    yourList.Sort(comparer);  // now contains { 18/01/2011, 23/01/2011, null, null }
    
    // ...
    
    public sealed class NullsLastComparer : Comparer
    {
        private readonly IComparer _comparer;
    
        public NullsLastComparer() : this(null) { }
    
        public NullsLastComparer(IComparer comparer)
        {
            _comparer = comparer ?? Comparer.Default;
        }
    
        public override int Compare(T x, T y)
        {
            if (x == null)
                return (y == null) ? 0 : 1;
    
            if (y == null)
                return -1;
    
            return _comparer.Compare(x, y);
        }
    }
    

提交回复
热议问题