Check if KeyValuePair exists with LINQ's FirstOrDefault

Steve picture Steve · Apr 27, 2009 · Viewed 62.4k times · Source

I have a dictionary of type

Dictionary<Guid,int>

I want to return the first instance where a condition is met using

var available = m_AvailableDict.FirstOrDefault(p => p.Value == 0)

However, how do I check if I'm actually getting back a KeyValuePair? I can't seem to use != or == to check against default(KeyValuePair) without a compiler error. There is a similar thread here that doesn't quite seem to have a solution. I'm actually able to solve my particular problem by getting the key and checking the default of Guid, but I'm curious if there's a good way of doing this with the keyvaluepair. Thanks

Answer

Marc Gravell picture Marc Gravell · Apr 27, 2009

If you just care about existence, you could use ContainsValue(0) or Any(p => p.Value == 0) instead? Searching by value is unusual for a Dictionary<,>; if you were searching by key, you could use TryGetValue.

One other approach:

var record = data.Where(p => p.Value == 1)
     .Select(p => new { Key = p.Key, Value = p.Value })
     .FirstOrDefault();

This returns a class - so will be null if not found.