我是C#的noobie,并且不明白为什么ContainsKey()
使用值bid_amount
和bid_amount
赢回原则。
我有一个长字符串("key=value, key=value...")
,它在,
上拆分,然后=
创建到字典中。但是,当我在dict bid_amount
中测试已知密钥时,它总是返回false。
有没有办法比较使用ContainsKey()的值? 究竟我错过了什么?
string[] responseStringSplit = responseString.Split (new []{ ',' });
Dictionary<string,string> responseDict = new Dictionary<string, string> ();
foreach (string word in responseStringSplit)
{
string[] splitString = word.Split (new[]{ ':' });
if (splitString.Length > 1)
{
responseDict.Add(splitString [0],splitString [1]);
}
else
{
Debug.Log ("CouldNotSplit:" + word);
}
}
foreach (KeyValuePair<string, string> entry in responseDict)
{
Debug.Log (entry.Key + "=" + entry.Value);
if (responseDict.ContainsKey ("bid_amount"))
{
Debug.Log ("found bid amount");
}
}
答案 0 :(得分:0)
根据您的输入,您在,
和key
之间留出了空格。尝试在splitString[0]
和splitString[1]
上调用.Trim(),然后再将其添加到字典中。
responseDict.Add(splitString[0].Trim(), splitString[1].Trim());
答案 1 :(得分:0)
如果仔细查看代码和输入,则有2个问题:
代码应该是:
//split by ", " (plus the space) to avoid that problem (or use trim)
string[] responseStringSplit = responseString.Split (new []{ ", " });
//split by "=" instead of current ":" (Or change input string from having '=' to ':')
string[] splitString = word.Split (new[]{ '=' });
除了改变这一点之外,当然欢迎为密钥添加Trim()
和ToLower()
以避免白色空格和大写/小写的问题