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
Use the default() keyword.
A way to check against the default value of a struct such as KeyValuePair without specifying the type is to create a new instance using Activator:
If you just care about existence, you could use
ContainsValue(0)
orAny(p => p.Value == 0)
instead? Searching by value is unusual for aDictionary<,>
; if you were searching by key, you could useTryGetValue
.One other approach:
This returns a class - so will be
null
if not found.you could check if
I suggest you change it in this way:
You can then see whether the list is empty or not, and take the first value if it's not, e.g.
Note that there's no real concept of a "first" entry in a dictionary - the order in which it's iterated is not well-defined. If you want to get the key/value pair which was first entered with that value, you'll need an order-preserving dictionary of some kind.
(This is assuming you actually want to know the key - if you're just after an existence check, Marc's solution is the most appropriate.)
What you want is an
Any
method that gives you the matching element as well. You can easily write this method yourself.