在处理Nullable类型时在LinQ中使用.HasValue(),有没有办法摆脱"可能的SystemInvalidException"?

rad*_*byx 0 c# nullable visual-studio-2010

我有一份清单Foo's.

Foo有一种CreateDate类型DateTime?

我想得到最老的Foo.我尝试了直观的方式,但我得到了一个可能System.InvalidOperationException.

DateTime oldestFoo = 
(from f in allFoos where f.CreateDate.HasValue select f.CreateDate.Value).Min(); 
Run Code Online (Sandbox Code Playgroud)

有没有我错过的东西或者这种方式不可能?

我可以在没有LinQ的情况下这样做,但我也想学习另一种方法.

DateTime oldestFoo = DateTime.MaxValue;
foreach (var foo in allFoos)
{
    if (foo.CreateDate.HasValue && oldestFoo > foo.CreateDate)
    {
        oldestFoo = (DateTime)foo.CreateDate;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

万一你仍然卡住了,你可能想考虑使用DefaultIfEmpty- 看看这是否有帮助:

DateTime oldestFoo = allFoos.Where(f => f.CreateDate.HasValue)
                            .Select(f => f.CreateDate.Value)
                            .DefaultIfEmpty(DateTime.MaxValue)
                            .Min();
Run Code Online (Sandbox Code Playgroud)

认为你想用GetValueOrDefault你的查询中,否则你将仍然有一个问题,如果第一次查询不返回任何结果的.