7

In my Linq query I have the following :

.Where(x => x.dtt_ref_no == dtt_ref) 

where x.dtt_ref_no is a nullable int
and dtt_ref is of type int.
What is the correct way to compare these two values?

0

2 Answers 2

9

Your code works as it is, if you use == on a int? and an int it will return false if the nullable doesn't contain a value. So it's the same as if you'd write:

.Where(x => x.dtt_ref_no.HasValue && x.dtt_ref_no.Value == dtt_ref) 

It's the same behaviour as Nullable<T>.Equals because the int will be converted to an int? implicitly on comparison.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh crap.. my bad. I was running the linq query against the incorrect object. Thanks!
According to the IDE, "the int will be converted to an int?" is incorrect. It claims to convert the int? to int (hover on the ==), although that makes it very obscure what causes false if the int? has no value!
0

You should use the Equals overload:

.Where(x => x.dtt_ref_no.Equals(dtt_ref)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.