X

Operator ‘==’ cannot be applied to operands of type ‘System.Collections.Generic.KeyValuePair‘ and ‘‘

linq

You are here beacause you probably got a Linq error, specifically Operator ‘==’ cannot be applied to operands of type ‘System.Collections.Generic.KeyValuePair‘ and ‘‘
So if you wish to do something like this to KeyValuePair using Linq

var item = myDictionary.FirstOrDefault(x => x.Key == 123);
if(item != null)
{
 //blah blah

}

You will get this error
Operator ‘!=’ cannot be applied to operands of type ‘System.Collections.Generic.KeyValuePair‘ and ‘‘

Since by default KeyValuePairs are struct.
To solve the issue we need to try out this

 var defaultVal = default(KeyValuePair);
var item = myDictionary.FirstOrDefault(x => x.Key == 123);
if(!item.Equals(defaultValue)
{
 //blah blah
}

Hope this helps 🙂

Categories: .NET Misc
Taswar Bhatti:
Related Post