C # using LINQ and Nullable Boolean

I have the following linq query that takes a text field that can be Y, N or DBnull and fills a boolean value? parameter with 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 

Problematic line

 (i.targetmet == "Y") ? true : ((i.targetmet == "N") ? false : null) 

After reading it, I found some documentation that says that the 2nd and 3rd arguments are inline, if they must be of the same type or be implicitly convertible to each other.

My question is: how do I get around this limitation to achieve the desired result?

I am relatively new to C #, so I don’t know all its features / capabilities yet.

+7
c # ternary-operator nullable implicit-conversion
source share
2 answers

My suggestion would be to replace it:

 (i.targetmet != null) ? (bool?)(i.targetmet == "Y") : null; 

the reason the compiler disagrees without the cast is that even if you store it in a structure with a zero value, the ternary operation checks the compatibility of the results using an implicit conversion.

Are true and false results treated as bool literals, not bool? , therefore, are implicitly converted to null . Listing, or bool? result bool? will make them comparable. The one I suggested has an implicit conversion between bool? and null , and this also works:

 (i.targetmet != null) ? (i.targetmet == "Y") : (bool?)null; 

Is this an implicit conversion between bool and bool? . I arbitrarily prefer the former.

+6
source share

Can you explicitly convert one or more expressions to bool? :

 (i.targetmet == "Y") ? true : ((i.targetmet == "N") ? (bool?)false : (bool?)null) 
+2
source share

All Articles