c# - 在 If 条件中内联 TryGetValue 并评估其值

标签 c# dictionary

有什么方法可以在 If 条件下将 TryGetValue 写在一行上。调用 TryGetValue 的正常方式是:

string value;
Dictionary.TryGetValue("Key", out value);
If(value == "condition") { ... }

我正在寻找的是这样的东西。

If(Dictionary.TryGetValue("Key", out string) == "Condition") { ... }

我知道该行行不通,但它显示了所需的结果。

有什么办法可以实现吗?

最佳答案

您需要先使用返回的 bool,然后您可以使用 out 参数(使用 >= C# 7):

if (Dictionary.TryGetValue("Key", out string value) && value == "Condition")
{
    //...
}

MSDN :

Starting with C# 7.0, you can declare the out variable in the argument list of the method call, rather than in a separate variable declaration.

如果您不使用 C#7 或者您希望它更短,您可以使用这个扩展:

public static bool TryEvaluateValue<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, Func<TValue, bool> evalValue)
{
    TValue val;
    if(!dict.TryGetValue(key, out val))
        return false;
    return evalValue(val);
}

然后你的if条件变成:

if (Dictionary.TryEvaluateValue("Key", value => value == "Condition"))
{
    //...
}

关于c# - 在 If 条件中内联 TryGetValue 并评估其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52362941/

相关文章:

c# - 对网站进行负载测试

c# - MVC Razor 路由建议

c# - 错误 SQL :The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Python 字典 : compare 2 values in 1 key

c# - ListView 中的项目没有行缩进

c# - 视觉 C++ : function definition for 'mouse_event' not found

list - 如何获取 List 的第一个元素,它本身是 Map [int, Any] 类型的 Map 的成员

Python 字典用于配对并使用字典检查反对称性

python - 将 JSON 从文件加载到 Python 字典的正确方法

python - 带有 if else hasattr 的 for 循环中的字典列表