在我的桌面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;
}
Run Code Online (Sandbox Code Playgroud)
Sel*_*enç 11
您可以使用ContainsKey方法检查密钥是否存在,如果返回false,则可以传递所需的default值:
// replace default(string) with the value you want to pass
// if the key doesn't exist
var value = myDic.ContainsKey(field1.field2) ? myDic[field1.field2] : default(string);
string text = SomeFunction(stringValue1, stringValue2, value);
Run Code Online (Sandbox Code Playgroud)
根据评论更新.要传递一个可能存在或不存在的密钥,您可以执行此操作(假设值为List):
// 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);
Run Code Online (Sandbox Code Playgroud)
无论字典是否存在,您是否希望传递整个字典(如最初读取的问题):
你有两个选择.无论是这样创建字典:
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);
Run Code Online (Sandbox Code Playgroud)
或者,可能是更好的选择,在函数声明中,SomeFunction将字典作为带有默认参数的变量添加.如果字典为null,请确保您的函数知道该怎么做.
string SomeFunction(string string1, string string2, Dictionary dictionary = null)
{
// method here
}
Run Code Online (Sandbox Code Playgroud)
您需要做的是确保字典实际上包含字典中的给定键。
如果需要通过键提取值,请使用TryGetValue方法:
string value;
if (myDict.TryGetValue(key, out value))
{
// Key exists in the dictionary, do something with value.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30194 次 |
| 最近记录: |