Dictionary ContainsKey()不会比较字符串值

时间:2016-08-02 05:29:59

标签: c# dictionary split

我是C#的noobie,并且不明白为什么ContainsKey()使用值bid_amountbid_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");
    }
}

2 个答案:

答案 0 :(得分:0)

根据您的输入,您在,key之间留出了空格。尝试在splitString[0]splitString[1]上调用.Trim(),然后再将其添加到字典中。

responseDict.Add(splitString[0].Trim(), splitString[1].Trim());

答案 1 :(得分:0)

如果仔细查看代码和输入,则有2个问题:

  1. 你首先分成&#34;,&#34;而你的输入代码是&#34; someText,someTextAfterSpace&#34; - 因此分为&#34;,&#34;。
  2. 然后你分成&#34;:&#34;而您的输入代码是&#34; =&#34;
  3. 代码应该是:

    //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()以避免白色空格和大写/小写的问题