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
.
int i;
results.TryGetValue(3, out i);
If it finds it, i
is set to the value. If not, i
is default, which will be zero for int.
If you want another value besides default, you can do this:
int i;
if (!results.TryGetValue(3, out i))
{
i = 5; // or whatever other value you want;
}
And if you, like me, hate the out
parameter style, you can create an extension method
public static class IDictionaryExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
T i;
dictionary.TryGetValue(key, out i);
return i;
}
}
and then you can call:
int i = dictionary.GetValueOrDefault(3);
and if you want to get fancier you can create another oveload of the extension:
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue)
{
T i;
return dictionary.TryGetValue(key, out i) ? i : defaultValue;
}
which can be called
int i = dictionary.GetValueOrDefault(3, 5);
Why not just
var t = results.ContainsKey(3) ? results[3] : 0;
and bypass the need for LINQ altogether?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With