2013-01-10 19 views
9

Mam dwa zerowalne obiekty datetime, chcę porównać oba. Jaki jest najlepszy sposób na zrobienie tego?Porównaj nullable datetime obiektów

Próbowałem już:

DateTime.Compare(birthDate, hireDate); 

To daje błąd, może to spodziewa termin typu System.DateTime i mam pustych datetimes.

Próbowałem również:

birthDate > hiredate... 

ale wyniki nie są zgodnie z oczekiwaniami ... jakieś sugestie?

+0

Czy zerowy zmbq

+0

W jaki sposób wyniki różnią się od oczekiwanych, gdy używasz 'birthDate> hireDate', ponieważ jest to najłatwiejszy sposób na zrobienie tego. C# wprowadził ** podnoszone operatory **, aby ułatwić Ci pracę. –

Odpowiedz

19

Aby porównać dwa Nullable<T> obiekty używać Nullable.Compare<T> jak:

bool result = Nullable.Compare(birthDate, hireDate) > 0; 

Można również zrobić:

użyć właściwości Wartość pustych DateTime. (Pamiętaj, aby sprawdzić, czy zarówno obiekt ma pewne wartości)

if ((birthDate.HasValue && hireDate.HasValue) 
    && DateTime.Compare(birthDate.Value, hireDate.Value) > 0) 
{ 
} 

Jeśli obie wartości są takie same DateTime.Compare zwróci Ci 0

Coś jak

DateTime? birthDate = new DateTime(2000, 1, 1); 
DateTime? hireDate = new DateTime(2013, 1, 1); 
if ((birthDate.HasValue && hireDate.HasValue) 
    && DateTime.Compare(birthDate.Value, hireDate.Value) > 0) 
{ 
} 
+3

Jeśli wartość null jest niepoprawna, otrzymasz wyjątek próbując uzyskać dostęp do właściwości wartości –

+0

Jakie wartości całkowite zostaną zwrócone w każdym przypadku, tj.><== – faizanjehangir

+0

Jeśli któraś z dat jest pusta, wartość .Value będzie równa zero i spowoduje odrzucenie wyjątek InvalidOperationException z "obiektem Nullable musi mieć wartość". OP może chcieć dodać tam kontrole zerowe. – ryadavilli

11

Nullable.Equals Wskazuje, czy określony dwa Obiekty Nullable (Of T) są równe.

Spróbuj:

if(birthDate.Equals(hireDate)) 

Najlepszym sposobem byłoby: Nullable.Compare Method

Nullable.Compare(birthDate, hireDate)); 
4

Jeśli chcesz wartość null być traktowane jako default(DateTime) mógłby zrobić coś takiego:

public class NullableDateTimeComparer : IComparer<DateTime?> 
{ 
    public int Compare(DateTime? x, DateTime? y) 
    { 
     return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault()); 
    } 
} 

i używać go w ten sposób

var myComparer = new NullableDateTimeComparer(); 
myComparer.Compare(left, right); 

Innym sposobem na to byłoby uczynić metodę rozszerzenia dla Nullable typów, których wartości są porównywalne

public static class NullableComparableExtensions 
{ 
    public static int CompareTo<T>(this T? left, T? right) 
     where T : struct, IComparable<T> 
    { 
     return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault()); 
    } 
} 

Jeżeli chcesz używać go tak jak to

DateTime? left = null, right = DateTime.Now; 
left.CompareTo(right); 
1

As @Vishal stwierdził, po prostu użyj overriden Equals method of Nullable<T>. Jest on realizowany w ten sposób:

public override bool Equals(object other) 
{ 
    if (!this.HasValue)  
     return (other == null); 

    if (other == null)  
     return false; 

    return this.value.Equals(other); 
} 

Zwraca true jeśli albo oba dopuszczające wartość null elemencie nie mają wartości, lub gdy ich wartości są równe.Tak, wystarczy użyć

birthDate.Equals(hireDate) 
1
Try birthDate.Equals(hireDate) and do your stuff after comparision. 
or use object.equals(birthDate,hireDate) 
1

Myślę, że można użyć warunku w następujący sposób

birthdate.GetValueOrDefault(DateTime.MinValue) > hireddate.GetValueOrDefault(DateTime.MinValue) 
3

użyć metody Nullable.Compare<T>. Tak:

var equal = Nullable.Compare<DateTime>(birthDate, hireDate); 
+0

Chociaż podoba mi się ta metoda, prawdopodobnie miałeś na myśli 'var equal = Nullable.Compare (birthDate, hireDate);' :) –

+0

Naprawdę, naprawione, dziękuję. – Maarten

0

można napisać metodę rodzajową obliczyć min lub max dla każdego typu jak poniżej:

public static T Max<T>(T FirstArgument, T SecondArgument) { 
    if (Comparer<T>.Default.Compare(FirstArgument, SecondArgument) > 0) 
     return FirstArgument; 
    return SecondArgument; 
} 

Następnie użyj jak poniżej:

var result = new[]{datetime1, datetime2, datetime3}.Max(); 
Powiązane problemy