KeyValuePair 的默认值

发布于 2024-08-09 10:31:04 字数 351 浏览 5 评论 0 原文

我有一个 IEnumerable> 类型的对象keyValueList,我正在使用

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

月寒剑心 2024-08-16 10:31:04

试试这个:

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

或者这个:

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

Try this:

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

or this:

if (getResult.Equals(default(KeyValuePair<T,U>)))
桃扇骨 2024-08-16 10:31:04

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

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'

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'
初吻给了烟 2024-08-16 10:31:04

试试这个:

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

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));
陌上芳菲 2024-08-16 10:31:04
if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))
if(getResult.Key.Equals(default(T)) && getResult.Value.Equals(default(U)))
水晶透心 2024-08-16 10:31:04

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

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

From your original code it looks like what you want is to check if the list was empty:

var getResult= keyValueList.SingleOrDefault();
if (keyValueList.Count == 0)
{
   /* default */
}
else
{
}
一瞬间的火花 2024-08-16 10:31:04

我建议使用扩展方法更容易理解:

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()){

}

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()){

}
眼眸里的那抹悲凉 2024-08-16 10:31:04

为了避免 KeyValuePair.Equals(object) 装箱,您可以使用 ValueTuple

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

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

if ((getResult.Key, getResult.Value) == default)
我的鱼塘能养鲲 2024-08-16 10:31:04

对于您的应用程序来说,检查键或值是否为默认值可能就足够了。例如,如果您有一个映射正值的KeyValuePair非零整数到字符串,并且字符串永远不会为空,那么:

if(getResult.Key == default)

if(getResult.Value == default)

将是已返回默认 KVP 的指示符

本质上,如果只需一个测试就可以,则可能不需要测试整个 KVP 是否为默认值;考虑您的用例

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

神爱温柔 2024-08-16 10:31:04

C# 8.0 或更高版本或 .NET Core 3.x.NET 5.x 或更高版本中使用模式匹配

//
// assume key is string and value is object
//

var getResult = keyValueList.SingleOrDefault();

// if clause
if (getResult is { Key: default(string), Value: default(object) })
{
    do_both_key_value_are_default();
}
// if clause negate
if (getResult is not { Key: default(string), Value: default(object) })
{
    do_both_key_value_found();
}


// switch style
switch (getResult)
{
    case { Key: default(string), Value: default(object) }: // this is default case where cannot find the single
        do_both_key_value_are_default();
        break;
    default:
        do_something_else();
        break;
}

using pattern match in C# 8.0 or above or .NET Core 3.x, .NET 5.x or above

//
// assume key is string and value is object
//

var getResult = keyValueList.SingleOrDefault();

// if clause
if (getResult is { Key: default(string), Value: default(object) })
{
    do_both_key_value_are_default();
}
// if clause negate
if (getResult is not { Key: default(string), Value: default(object) })
{
    do_both_key_value_found();
}


// switch style
switch (getResult)
{
    case { Key: default(string), Value: default(object) }: // this is default case where cannot find the single
        do_both_key_value_are_default();
        break;
    default:
        do_something_else();
        break;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文