When you have a Dictionary<TKey, TValue>, then LINQ results will get you a enumerables of KeyValuePair<TKey, TValue>.
Since KeyValuePair is a struct, selecting FirstOrDefault will not get you a null, but a default(KeyValuePair<TKey, TValue>) which is a lot harder to handle than null.
Sometimes, being able to get a null out of FirstOrDefault is very useful, so a bit thank you to Marc Gravell for answering this very neat trick:
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:
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.
The trick is this portion:
p => new { Key = p.Key, Value = p.Value }
It introduces an anonymous type with two fields: Key and Value. (Note you can introduce any anonymous type here). Since these are classes, FirstOrDefault will return null if nothing was found.
–jeroen
via: