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
default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .
KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.
The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.
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.
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