c# 检查键是否存在于字典中然后传递它的值

标签 c# dictionary

在我的桌面 C# 应用程序中,我从字典开始。我希望能够检查这本字典的关键。如果字典有这个键,我想把它传递给一个方法。如果字典没有这个键,我想创建一个空白列表并将其传递给它。我该怎么做?

我收到错误消息“字典中不存在给定的键”。我可以添加一个默认值,使其永远不会为 null 吗?

// myDic was declared as a Dictionary<string, List<string>    

// Here is how I call someFunction
string text = SomeFunction(stringValue1, stringValue2, myDic[field1.field2]);

// SomeFunction looks like this
string SomeFunction (string string1, string string2, List<string> ra) 
{  
     // method 
     return stringResult;
} 

最佳答案

根据评论更新。要传递一个可能存在也可能不存在的键,您可以这样做(假设值是一个列表):

// assuming the method we are calling is defined like this:
// public String SomeFunction(string string1, String string2, List<String> ra)  

List<string> valueToPassOn;
if (_ra.ContainsKey(lc.Lc))
{
     valueToPassOn = _ra[lc.Lc]
}
else
{
     valueToPassOn = new List<string>(); 
}

string text = tooltip.SomeFunction(something1, something2, valueToPassOn); 

是否要传递整个字典(如问题最初所读),而不管字典是否存在:

您有两个选择。要么像这样创建字典:

if (myDic == null)
{
     // change var and var2 to the types of variable they should be, ex:
     myDic = new Dictionary<string, List<string>>();
}
string text = SomeFunction(stringValue1, stringValue2, myDic);

或者,什么可能是更好的选择,在函数 SomeFunction 的声明中添加一个字典作为具有默认参数的变量。只需确保您的函数知道如果字典为 null 时该怎么做。

string SomeFunction(string string1, string string2, Dictionary dictionary = null)
{
     // method here
}

关于c# 检查键是否存在于字典中然后传递它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826482/

相关文章:

c# - 十进制类型的声明后缀

c# - 使用 Rijndael 解密时 C# 和 PHP 的不同结果

python - 访问字典中数组中嵌套的数据

python - 在 Django 模板中循环字典的字典只需 1 行代码

python - 通过传递列表来索引字典

python - Python 的 dict.pop 是原子的吗?

javascript - 如何将标签转移到另一个容器

c# - 使用 Min 或 Max 时如何处理 LINQ 中的空值?

c# - 使用 .NET 进行 Java RSA/ECB/PKCS1Padding 加密

python - 检查值是否存在于数据框中并在字典中找到它