我有一个日期列表,我想按升序排序。但是,默认比较器意味着我有:
null
null
18/01/2011
23/01/2011
有人可以帮助IComparer,这意味着按升序排序的日期将如下所示:
18/01/2011
23/01/2011
null
null
答案 0 :(得分:17)
这是一个适用于几乎任何类型的通用比较器:
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);
}
}
答案 1 :(得分:5)
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
}
不需要额外的空检查。
答案 2 :(得分:1)
你可以试试这个:
messages.Sort((x, y) => (x.CreatedOn ?? DateTime.MaxValue).CompareTo(y.CreatedOn ?? DateTime.MaxValue));