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

我的未来我决定 提交于 2019-12-21 02:38:34

问题


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

Can someone help with a IComparer that will mean that the dates sorted in ascending order will look like:

18/01/2011
23/01/2011
null
null

回答1:


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

var yourList = new List<DateTime?>
                   {
                       null, new DateTime(2011, 1, 23),
                       null, new DateTime(2011, 1, 18)
                   };

var comparer = new NullsLastComparer<DateTime?>();
yourList.Sort(comparer);  // now contains { 18/01/2011, 23/01/2011, null, null }

// ...

public sealed class NullsLastComparer<T> : Comparer<T>
{
    private readonly IComparer<T> _comparer;

    public NullsLastComparer() : this(null) { }

    public NullsLastComparer(IComparer<T> comparer)
    {
        _comparer = comparer ?? Comparer<T>.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);
    }
}



回答2:


public class DateTimeComparer : IComparer<DateTime?>
{
    #region IComparer<DateTime?> 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.




回答3:


You could try this:

messages.Sort((x, y) => (x.CreatedOn ?? DateTime.MaxValue).CompareTo(y.CreatedOn ?? DateTime.MaxValue));


来源:https://stackoverflow.com/questions/4734055/c-sharp-icomparer-if-datetime-is-null-then-should-be-sorted-to-the-bottom-no

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!