比较DateTime的Date属性?

Mr *_*ose 0 .net comparison datetime

我想尝试比较两种类型的DateTime相对干净的方法?对象无需烦扰大量的空检查.

以下是一个好主意,或者有一个更简单或明智的方法来实现它;

DateTime? test = DateTime.MinValue;
DateTime? date1 = new DateTime(2008, 6, 1, 7, 47, 0);

if (string.Format("{0:MM/dd/yyyy}", date1) == string.Format("{0:MM/dd/yyyy}", test))
{
    Console.WriteLine("They are the same");
}
else
{
     Console.WriteLine("They are different");
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

不,使用文本格式来比较简单值不是一个好主意IMO.使事情变得更整洁的一个选择是编写一个扩展方法来有效地传播空值(如monad):

public static Nullable<TResult> Select<TSource, TResult>
    (this Nullable<TSource> input, Func<TSource, TResult> projection)
    where TSource : struct
    where TResult : struct
{
    return input == null ? (Nullable<TResult>) null : projection(input.Value);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以轻松地比较可空类型的投影:

if (date1.Select(x => x.Date).Equals(date2.Select(x => x.Date))
Run Code Online (Sandbox Code Playgroud)

甚至可以添加自己的相等投影方法:

public static bool EqualsBy<TSource, TResult>
    (this Nullable<TSource> x, Nullable<TSource> y,
     Func<TSource, TResult> projection)
    where TSource : struct
    where TResult : struct
{
    return x.Select(projection).Equals(y.Select(projection));
}
Run Code Online (Sandbox Code Playgroud)

和:

if (date1.EqualsBy(date2, x => x.Date))
Run Code Online (Sandbox Code Playgroud)

当您真的不关心文本时,这比执行文本转换更加灵活和优雅.