【问题标题】:C# How do you loop through multiple dictionaries?C#如何循环遍历多个字典?
【发布时间】:2017-05-26 05:41:12
【问题描述】:

一个标准的字典应该是这样的:

        public Dictionary<int, DictionarySetup> H = new Dictionary<int, DictionarySetup>()
        {
            {18000, new DictionarySetup { Some values }},
        };

从 A 到 T,所有这些都在一个名为 DictionaryInit 的类中,现在我检查该值是否与此布尔值匹配:

public Boolean Dictionary_Test(Dictionary<int, DictionarySetup> AccountLexicon)
    {
        DictionarySetup ClassValues;
        if (AccountLexicon.TryGetValue(MapKey, out ClassValues))
        {
            return true;
        }
        return false;
    }

现在,我正在寻找一种更有效的方法来遍历每个字典,如果有匹配项,则获取该特定字典以在后续方法中使用,这就是它现在在 if/else 中的样子:

            if(Dictionary_Test(theDictionary.C) == true)
            {
              Dictionary_Find(Account_String, rowindex, theBSDictionary.C, Cash_Value, txtCurrency.Text);
            }
            else if (Dictionary_Test(theDictionary.D) == true)
            {
                Dictionary_Find(Account_String, rowindex, theDictionary.D, Cash_Value, txtCurrency.Text); //Method that makes use of the dictionary values, above dictionary checks only if it exists
            }

如果使用 A-T 的字典,那将是很多 if/else 的!有一个更好的方法吗?我发现一个线程提到了同样的主题,通过将字典添加到字典数组 [] 然后循环遍历它,但是如果找到匹配项,我如何获取匹配字典的名称或使用我的第二种方法 Dictionary_Find,使用匹配字典?

【问题讨论】:

  • 为什么不只是一个字典列表,而不是dictionary_A-T?

标签: c# loops dictionary


【解决方案1】:

另一种可能的解决方案,您可以使用反射从 DictionaryInit 类的 A-T 中获取每个字典。创建一个包含值 A-T 的数组,遍历数组并使用反射来获取字典,并测试该字典,如果找到匹配项,则返回该字典并退出循环。比如:

var dicts = new[]{"A", "B", ......., "T"}

foreach (var dict in dicts)
{
    var found = CheckDictionary(theDictionary, dict);
    if (found != null)
    {
        Dictionary_Find(Account_String, rowindex, (Dictionary<int, DictionarySetup>)found, Cash_Value, txtCurrency.Text);
        break;
    }
}

public static object CheckDictionary(object dictClass, string dictName)
{
   var theDictionary = dictClass.GetType().GetProperty(dictName).GetValue(dictClass, null);
    return Dictionary_Test(theDictionary) ? theDictionary : null;
}

我刚刚从一个我完成的项目中快速获取了一些代码,并对其进行了修改以适应但尚未对其进行测试。可能需要一些调整,但希望能让你接近!

【讨论】:

    【解决方案2】:
    // put dictionary A ~ T to a list of dictionary
    List<Dictionary<int, DictionarySetup>> dictionaries = new List<Dictionary<int, DictionarySetup>>{A,B,C, ... , T}; // Replace ... with D,E,F, etc. until T
    // iterate each dictionary and if found, exit the loop
    foreach(var dict in dictionaries)
    {
       if(Dictionary_Test(dict))
       {
          Dictionary_Find(Account_String, rowindex, dict, Cash_Value, txtCurrency.Text);
          break;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-10
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多