可为空日期时间的 linq
我有一个包含 Time1 和 Time2 的表(为了示例)。 Time2 允许空值。
我有一个对象模型,我希望 Time2 可以为空;到目前为止,我有这个:
public Class MyModel{
public DateTime Time1 {get;set;}
public System.Nullable<DateTime> Time2 {get;set}
}
当我转到查询时,我有这个:
var MyQuery = ...
select new MyModel()
{
Time2 = (a.Time2)
在这里我想知道是否应该使用 SingleOrDefault 运算符?它没有显示在智能感知中。然而,智能感知显示了其他几个选项,其中包括:HasValue、Value、GetValueOrDefault。
关于什么是正确的选择有什么想法吗?
谢谢
I have a table that has Time1 and Time2 (for the sake of example). Time2 allows for nulls.
I have an object model and I want to have Time2 as nullable; so far I have this:
public Class MyModel{
public DateTime Time1 {get;set;}
public System.Nullable<DateTime> Time2 {get;set}
}
When I go to my query, I have this:
var MyQuery = ...
select new MyModel()
{
Time2 = (a.Time2)
and here I'm wondering if I should have the SingleOrDefault operator? It's not showing in the intellisense. Howver, the intellisense is showing several other options, amongst whic are: HasValue, Value, GetValueOrDefault.
Any ideas on what's the right one to choose from?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是因为 Time2 是可为 null 的类型。可空类型始终具有值属性。如果将行修改为:
然后按 Value 后面的句点符号,您将看到 Intellisense 弹出窗口。
作为安全检查,您可能还需要在使用 .Value 之前检查 a.Time2 的值是否不为 null。否则你会得到一个空引用异常
That's because Time2 is a nullable type. Nullable types always have a value property. If you revise your line to:
and then press the period symbol after Value, you'll see the Intellisense pop up.
As a safety check you may want to also check that the value of a.Time2 is not null, before using .Value. Otherwise you'll get a null reference exception
SingleOrDefault 是通用 IEnumerable 的扩展方法,如下所示。
<代码>
公共静态 TSource SingleOrDefault(
这个 IEnumerable 来源)
如果您有一些可为 Nullable 的列表,您可以使用该方法,并且如果该列表没有或多个项目,它将返回第一个值或抛出异常。
这可能不是您想要的,您想要某个值为 null 的值,那么您应该使用 C# 3.0 的合并运算符或 Nullable<> 中的 GetValueOrDefault 方法的重载之一。类型。
SingleOrDefault is a extension method for the generic IEnumerable as you see below.
public static TSource SingleOrDefault(
this IEnumerable source)
If you had some list of Nullable you could use that method and it would return the first value or throws if the list had none or more than one item.
That is probably not what you want, you want some value when it is null, then you should use either the coalesce operator of C# 3.0 or one of the overloads of the GetValueOrDefault method from Nullable<> type.
您为什么认为您应该拥有一个针对
System.Nullable
上的集合项存在的方法。您不会对此使用
SingleOrDefault()
。Time2 = (a.Time2.HasValue ? a.Time2.Value : null)
这就是您应该如何设置该值或将其设置为 null 的方式。
Why do you think that You should have a method that exists for items of a collection on something that is a
System.Nullable<DateTime>
.You won't have
SingleOrDefault()
on this.Time2 = (a.Time2.HasValue ? a.Time2.Value : null)
That's how you should set the value or have it be null.