The default for KeyValuePair

Viewed 211173

I have an object of the type IEnumerable<KeyValuePair<T,U>> keyValueList, I am using

 var getResult= keyValueList.SingleOrDefault();
 if(getResult==/*default */)
 {
 }
 else
 {
 } 

How can I check whether getResult is the default, in case I can't find the correct element?

I can't check whether it is null or not, because KeyValuePair is a struct.

8 Answers

To avoid the boxing of KeyValuePair.Equals(object) you can use a ValueTuple.

if ((getResult.Key, getResult.Value) == default)

It may suffice, for your application, to check if either the Key, or the Value are default.. For example if you have a KeyValuePair<int,string> mapping positive nonzero integers to strings, and the strings are never null, then either:

if(getResult.Key == default)

if(getResult.Value == default)

Would be an indicator that a default KVP has been returned

In essence, there may be no need to test the whole KVP for being default, if just one test will do; consider it for your use case

Related