c# - linq .Value Nullable Object must have a value. How to skip? -
i have linq code null
:
cbo3.itemssource = empty.union(from in (from b in completedata select b.touropid).distinct() select new comboboxitemstring() { valuestring = a.value.tostring() });
but touropid
null
throwing error on a.value.tostring()
. how solve this?
the problem occurs because access value
property of nullable
type null
(or, more precisely, hasvalue
property false
). how fix depends on want do:
if want filter out items
touropid
null, addwhere
clause:... (from b in completedata b.touropid != null // filter select b.touropid).distinct() ...
if want use replacement value, e.g.
0
, iftouropid
null, use null coalescing operator??
, convertsint?
int
:... (from b in completedata select b.touropid ?? 0).distinct() ...
or, alternatively,
... select new comboboxitemstring() { valuestring = a.getvalueordefault().tostring() });
if want show different combobox entry if
touropid
null, use ternary operator?:
:... select new comboboxitemstring() { valuestring = (a == null ? "no tour operator" : a.value.tostring()) });
if want show empty string if
a
null, solution simpler:... select new comboboxitemstring() { valuestring = a.tostring() });
since nullable.tostring returns empty string if not have value.
Comments
Post a Comment