我有一些 linq 代码,有时null
:
cbo3.ItemsSource = empty.Union(from a in
(from b in CompleteData
select b.TourOpID).Distinct()
select new ComboBoxItemString() { ValueString = a.Value.ToString() });
But TourOpID
有时是null
抛出错误a.Value.ToString()
。我该如何解决这个问题?
出现此问题的原因是您访问Value财产 http://msdn.microsoft.com/en-us/library/ydkbatt6.aspx of a Nullable
类型是null
(或者,更准确地说,谁的HasValue
财产是false
)。如何解决此问题取决于您想要执行的操作:
-
如果您想过滤掉其中的项目TourOpID
为空,只需添加一个where
clause:
...
(from b in CompleteData
where b.TourOpID != null // filter
select b.TourOpID).Distinct()
...
-
如果您想使用替换值,例如0
, if TourOpID
为空,使用空合并运算符 http://msdn.microsoft.com/en-us/library/ms173224.aspx ??
,这将转换你的int?
进入一个int
:
...
(from b in CompleteData
select b.TourOpID ?? 0).Distinct()
...
或者,或者,
...
select new ComboBoxItemString() { ValueString = a.GetValueOrDefault().ToString() });
-
如果您只想显示不同的 ComboBox 条目TourOpID
为空,使用三元运算符?:
:
...
select new ComboBoxItemString() {
ValueString = (a == null ? "no tour operator" : a.Value.ToString())
});
如果你想显示空字符串 ifa
为 null,解决方案更简单:
...
select new ComboBoxItemString() { ValueString = a.ToString() });
since Nullable.ToString http://msdn.microsoft.com/en-us/library/9hd15ket.aspx如果没有值,则返回空字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)