Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to objects: if number is in dictionary, return number, else return 0

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.

like image 683
Garth Marenghi Avatar asked Dec 16 '22 12:12

Garth Marenghi


2 Answers

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);
like image 98
Samuel Neff Avatar answered May 10 '23 04:05

Samuel Neff


Why not just

var t = results.ContainsKey(3) ? results[3] : 0;

and bypass the need for LINQ altogether?

like image 43
Cameron Avatar answered May 10 '23 05:05

Cameron