【问题标题】:Dictionary ContainsKey() Doesn't compare string valuesDictionary ContainsKey() 不比较字符串值
【发布时间】:2016-08-02 05:29:59
【问题描述】:

我是 C# 的菜鸟,不明白为什么 ContainsKey() 不会在值 bid_amountbid_amount 时返回 true。

我有一个长字符串("key=value, key=value..."),它在, 上拆分,然后= 创建到字典中。但是,当我在字典 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");
    }
}

【问题讨论】:

  • 你能告诉我们你的输入字符串吗?
  • 你确定有这样的字符串吗?我的意思是,它周围没有空间?也许您可以在添加 spitstring[0], [1] 周围的键/值对之前添加 Trim
  • 为我工作。检查您的输入。请参阅此处以获取具有有效输入的代码的工作示例:dotnetfiddle.net/SxOJ8M

标签: c# dictionary split


【解决方案1】:

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

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

【讨论】:

  • 是的,有一个尾随空格并且 .Trim() 修复了它。谢谢。
【解决方案2】:

如果您仔细查看代码并输入,您会遇到 2 个问题:

  1. 您首先用“,”分割,而您的输入代码是“someText, someTextAfterSpace” - 所以用“,”分割。
  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()s 和 ToLower() 作为密钥,以避免出现空格和大写/小写问题

【讨论】:

    猜你喜欢
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2013-03-23
    相关资源
    最近更新 更多