2011-01-19 10 views
6

Mam listę dat, które chcę sortować w porządku rosnącym. Jednak domyślne comparer oznacza, że ​​mam:C# - IComparer - Jeśli datetime ma wartość null, należy posortować ją na dół, nie na górę

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

Czy ktoś może pomóc z IComparer która będzie oznaczać, że terminy posortowane w kolejności rosnącej będzie wyglądać następująco:

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

Dzięki, David

+3

Czy twoje "terminy" faktycznie 'Nullable '/'DateTime' czy to są struny? – LukeH

+0

Są to DateTime? –

Odpowiedz

17

Oto generic comparer który powinien działać na prawie każdym rodzaju:

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

+1 dużo wolą ogólne rozwiązanie. –

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 
} 

Nie jest wymagane dodatkowe sprawdzanie zerowe.

+1

Nice. Dlaczego nie skrócić do 'DateTime nx = x ?? DateTime.MaxValue; ' – Ani

+0

Czy to możliwe, czy nie rozważyłeś użycia opcji zerowej? typy lol! –

1

Można spróbować to:

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