使用 LINQ 和 Nullable Boolean 的 C#
我有下面的 linq 查询,它采用可能是 Y、N 或 DBnull 的文本字段并填充布尔值?参数为 True、False 或 null,具体取决于字段的值。
var dset = from i in tbdc.Talkbacks
where i.talkback_id == id
select new Talkback(
i.talkback_id, i.acad_period, i.reference,
i.staff_member, i.date_received, i.no_talkers,
i.gender_id, i.names, i.type_id,
i.method_id, i.area_id, i.site_id,
i.category_id, i.date_closed, i.expenddate,
i.acknowledgementtarget,
(i.targetmet == "Y") ? true :
((i.targetmet == "N") ? false : null),
(i.acknowledgementtargetmet != "N") ? true : false
有问题的行是
(i.targetmet == "Y") ? true : ((i.targetmet == "N") ? false : null)
阅读完后我发现一些文档指出内联的第二个和第三个参数是否需要具有相同的类型或可以隐式地相互转换。
我的问题是,如何克服这个限制以达到我想要的结果?
我对 C# 比较陌生,所以还不熟悉它的所有怪癖/功能。
I have the below linq query which takes a text field which may be Y, N or DBnull and populates a boolean? parameter with either True, False or null depending on the value of the field.
var dset = from i in tbdc.Talkbacks
where i.talkback_id == id
select new Talkback(
i.talkback_id, i.acad_period, i.reference,
i.staff_member, i.date_received, i.no_talkers,
i.gender_id, i.names, i.type_id,
i.method_id, i.area_id, i.site_id,
i.category_id, i.date_closed, i.expenddate,
i.acknowledgementtarget,
(i.targetmet == "Y") ? true :
((i.targetmet == "N") ? false : null),
(i.acknowledgementtargetmet != "N") ? true : false
The problematic line is
(i.targetmet == "Y") ? true : ((i.targetmet == "N") ? false : null)
After reading up I found some documentation which states that the 2nd and 3rd arguments of the inline if need to be of the same type or be implicitly convertible to one another.
My question is, how do I get around this limitation to achieve my desired result?
I am relatively new to C# so am not familiar with all its quirks/capabilities yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是将其替换为 :
编译器在没有强制转换的情况下不同意的原因是,即使将其存储到可为空的结构中,三元操作也会通过隐式转换检查结果是否兼容。
结果
true
和false
被视为bool
文字,而不是bool?
,因此不能隐式转换为空
。将任一结果转换为bool?
将使它们具有可比性。我建议的在bool?
和null
之间有一个隐式转换,这也有效:这是一个
bool
和 <代码>布尔?。我个人比较喜欢第一个..My suggestion would be to replace it with :
the reason why the compiler does not agree without the cast is that even if you store it into a nullable structure, the ternary operation checks if the results are compatible through an implicit conversion.
Results
true
andfalse
are treated asbool
literals, notbool?
, thus not implicitly convertible tonull
. Casting either results tobool?
will make them comparable. The one I suggested has an implicit convertion betweenbool?
andnull
, and this works too:Which is an implicit conversion between a
bool
andbool?
. I arbitrary prefer the first one..您可以将一个或多个表达式显式转换为
bool?
:You can explicitly convert one or more of the expressions to a
bool?
: