I have a Dictionary<int int>. When I check the keys of the Dictionary for a number and it is in it, I want it to return the number, else I want the linq query to return 0.
Something like the following, except working
var t = (from result in results
where result.Key == 3
select result.Key != null ? result.Value : 0).First();
Because the problem is that when there is no number in the list, the sequence contains no element, so you can’t check with a null or a count.
Just use
TryGetValue.If it finds it,
iis set to the value. If not,iis default, which will be zero for int.If you want another value besides default, you can do this:
And if you, like me, hate the
outparameter style, you can create an extension methodand then you can call:
and if you want to get fancier you can create another oveload of the extension:
which can be called