linq .Value可为空的对象必须具有一个值.如何跳过?
我有一些linq代码,有时是null
:
I have some linq code that is sometimes null
:
cbo3.ItemsSource = empty.Union(from a in
(from b in CompleteData
select b.TourOpID).Distinct()
select new ComboBoxItemString() { ValueString = a.Value.ToString() });
但是TourOpID
有时null
在a.Value.ToString()
上引发错误.我该如何解决?
But TourOpID
is sometimes null
throwing an error on a.Value.ToString()
. How do I solve this?
发生此问题是因为您访问Nullable类型的Nullable
类型的="noreferrer"> Value
属性(或更准确地说,其HasValue
属性为false
).如何解决此问题取决于您要执行的操作:
The problem occurs because you access the Value
property of a Nullable
type which is null
(or, more precisely, whose HasValue
property is false
). How to fix this depends on what you want to do:
-
如果要过滤出
TourOpID
为null的项目,只需添加where
子句:
If you want to filter out items where
TourOpID
is null, just add awhere
clause:
...
(from b in CompleteData
where b.TourOpID != null // filter
select b.TourOpID).Distinct()
...
如果要使用替换值,例如0
,如果TourOpID
为空,请使用空合并运算符 ??
,它将您的int?
转换为int
:
If you want to use a replacement value, e.g. 0
, if TourOpID
is null, use the null coalescing operator ??
, which converts your int?
into an int
:
...
(from b in CompleteData
select b.TourOpID ?? 0).Distinct()
...
或者,或者,
...
select new ComboBoxItemString() { ValueString = a.GetValueOrDefault().ToString() });
如果在TourOpID
为null的情况下只想显示另一个ComboBox条目,请使用三元运算符?:
:
If you just want to show a different ComboBox entry if TourOpID
is null, use the ternary operator ?:
:
...
select new ComboBoxItemString() {
ValueString = (a == null ? "no tour operator" : a.Value.ToString())
});
如果要在a
为null时显示空字符串,则解决方案甚至更简单:
If you want to show the empty string if a
is null, the solution is even simpler:
...
select new ComboBoxItemString() { ValueString = a.ToString() });
因为 Nullable.ToString 返回空字符串(如果没有)有一个值.
since Nullable.ToString returns an empty string if it does not have a value.