C#如何遍历多个词典?

时间:2017-05-26 05:41:12

标签: c# loops dictionary

标准字典如下所示:

        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&#39; s!有一个更好的方法吗?我找到了一个提到同一主题的线程,通过将字典添加到字典数组[]然后循环遍历它,但是如果找到匹配或如何找到匹配字典,我该如何获取匹配字典的名称, Dictionary_Find,使用匹配的字典?

2 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分:0)

// 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;
   }
}