KeyValuePair的默认值

时间:2009-10-29 03:02:38

标签: c# key-value

我有IEnumerable<KeyValuePair<T,U>> keyValueList类型的对象,我正在使用

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

如果我找不到正确的元素,如何检查getResult是否为默认值?

我无法检查它是否为null,因为KeyValuePair是一个结构。

8 个答案:

答案 0 :(得分:491)

试试这个:

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

或者这个:

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

答案 1 :(得分:88)

您可以创建一般(和通用)扩展方法,如下所示:

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

        return isDefault;
    }
}

用法:

// 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'

答案 2 :(得分:22)

试试这个:

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));

答案 3 :(得分:17)

从C#7.1开始,您可以使用the default literal with type inference来简化表达式:

var getResult= keyValueList.SingleOrDefault();

if(getResult.Equals(default))
{
}
else
{
} 

答案 4 :(得分:8)

if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))

答案 5 :(得分:6)

从您的原始代码看起来您​​想要检查列表是否为空:

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

答案 6 :(得分:5)

我建议使用扩展方法更多的理解方式:

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

然后使用:

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

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

if(country.IsNull()){

}

答案 7 :(得分:1)

要避免将KeyValuePair.Equals(object)装箱,可以使用ValueTuple

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