The default for KeyValuePair

2019-01-10 07:34发布

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.

标签: c# key-value
7条回答
We Are One
2楼-- · 2019-01-10 08:17

As of C# 7.1, you can use the default literal with type inference to simplify the expression:

var getResult= keyValueList.SingleOrDefault();

if(getResult.Equals(default))
{
}
else
{
} 
查看更多
【Aperson】
3楼-- · 2019-01-10 08:19
if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))
查看更多
不美不萌又怎样
4楼-- · 2019-01-10 08:20

Try this:

if (getResult.Equals(new KeyValuePair<T,U>()))

or this:

if (getResult.Equals(default(KeyValuePair<T,U>)))
查看更多
女痞
5楼-- · 2019-01-10 08:20

Try this:

KeyValuePair<string,int> current = this.recent.SingleOrDefault(r => r.Key.Equals(dialog.FileName) == true);

if (current.Key == null)
    this.recent.Add(new KeyValuePair<string,int>(dialog.FileName,0));
查看更多
你好瞎i
6楼-- · 2019-01-10 08:20

I recommend more understanding way using extension method:

public static class KeyValuePairExtensions
{
    public static bool IsNull<T, TU>(this KeyValuePair<T, TU> pair)
    {
        return pair.Equals(new KeyValuePair<T, TU>());
    }
}

And then just use:

var countries = new Dictionary<string, string>
{
    {"cz", "prague"},
    {"de", "berlin"}
};

var country = countries.FirstOrDefault(x => x.Key == "en");

if(country.IsNull()){

}
查看更多
何必那么认真
7楼-- · 2019-01-10 08:21

You can create a general (and generic) extension method, like this one:

public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}

Usage:

// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'
查看更多
登录 后发表回答