【问题标题】:Searching a String in a Dictionary在字典中搜索字符串
【发布时间】:2014-09-11 09:40:24
【问题描述】:

我有这个 Class Form1.cs 我在其中创建了我的 GUI,它还有一个具有以下功能的组合框:

string SelectedItemName = (string)comboBox2.SelectedItem.ToString();
Console.WriteLine(SelectedItemName);
if (comboBox2.SelectedIndex > -1)
{
    testvariabel2.GetSessionName();
}

所以我检查用户是否从 ComboBox 中选择了某些内容,然后在我的其他类 CTestRack.cs 中调用函数 GetSessionName。

Dictionary<string, Dictionary<string, string>> newDictionary = new Dictionary<string,Dictionary<string, string>>();

foreach (SectionData section  in data.Sections)
{
    var keyDictionary = new Dictionary<string, string>();
    foreach (KeyData key in section.Keys)
        keyDictionary.Add(key.KeyName.ToString(), key.Value.ToString());

    newDictionary.Add(section.SectionName.ToString(), keyDictionary);

    if (newDictionary.ContainsKey(testvariabel.SelectedItemName))
    {
        Console.WriteLine("Key: {0}, Value: {1}", keyDictionary[testvariabel.SelectedItemName]);
    }
    else Console.WriteLine("Couldn't check Selected Name");
}

在这里,我想检查我的字典中是否存在 String SelectedItemName,但我总是收到 Systen.ArgumentNullException,即我的 CTestRackClass 中的 String SelectedItemName 为 NULL。

现在我的问题是,如何在 CTestRack 中的字典中搜索其他类中设置的字符串 表格1?

【问题讨论】:

标签: c# string linq dictionary


【解决方案1】:

嗯...实际上你查字典是对的!要查明字典中是否存在某个键,请使用ContainsKey

if(myDictionary.ContainsKey(myKey))
{
    //do something
}

但是,您的问题来自这样一个事实,即 null 从来都不是字典中的有效键(主要是因为 null 没有正确的哈希码)。因此,您需要确保您要查找的密钥不为空。从您的代码中,我猜testvariabel.SelectedItemName 没有按应有的设置。

此外,还有一种更有效的方法可以在对某个值进行操作之前查看它是否存在。使用TryGetValue

TValue val;
if(myDictionary.TryGetValue(myKey, out val))
{
    //do something with val
}

这样您就不需要访问 myDictionary[myKey]。如果你使用ContainsKey,你实际上是在访问同一个值两次。在大多数情况下,这是一个很小的成本,但很容易避免,所以你应该尝试一下。

请注意,我只回答了有关查字典的具体问题。关于整个代码的正确性,我无话可说。

【讨论】:

  • 我知道 null 不是一个有效的键,我还写下了我如何设置变量 SelectedItemName 的代码:“string SelectedItemName = (string)comboBox2.SelectedItem.ToString();”你认为它被错误地解决了吗?因为通常我想使用 String SelectedItemName 来制作 TryGetValue
  • string SelectedItemName = (string)comboBox2.SelectedItem.ToString(); 没有设置属性testvariabel.SelectedItemName,它创建了一个您之后似乎不再使用的新变量...
【解决方案2】:

我发现您的代码有两个明显的问题。

  1. 您正在检查一个键是否存在于一个字典 (newDictionary) 中,但试图从另一个字典 (keyDictionary) 中检索它
  2. 您甚至在字典完全构建之前就尝试在字典中查找键。将 if 检查移到 foreach 循环之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2023-03-13
    • 2016-11-30
    • 2013-07-24
    相关资源
    最近更新 更多