嵌套字典的递归

时间:2015-06-19 02:50:45

标签: c# dictionary recursion

我有一个包含倍数值的字典。我的字典是:

public class checkitems: Dictionary<int, checkitems>{
  // ....
}

我正在这样循环每个级别。

foreach(KeyValuePair<int, checkitems> first in items){
   foreach(KeyValuePair<int, checkitems> second in first.values){
       foreach(KeyValuePair<int, checkitems> third in second.values){
          List<int> list1 = new List<int>(); 
          if(third.Value.Age > 20){ 
              list.Add(x.key)
           }
        }
        foreach(var deleteKeys in list1){
        second.Value.Remove(deleteKeys)
        }
    }
}

目前我正在为每个级别编写foreach并检查它是否满足条件,然后将其添加到列表中以进行删除。我想知道如何递归地写它,以便我不必担心水平有多深。

Example data format:
    Companies 
         i. Apple
            a. key: Macbookpro   Value: 200
            b (key): IMAC        Value: 334
            c (key): Iphone      Value : 12
                1. (key) IOS8    Value : 13
                2. (key) IOS7    Value : 15
            d (key): Beats       Value: 20

2 个答案:

答案 0 :(得分:1)

我尽力理解你的代码试图实现的目标。希望这有帮助

SELECT COUNT(*) FROM myTable 
GROUP BY ??

答案 1 :(得分:0)

给定root checkitems个实例,试试这个:

Func<checkitems, IEnumerable<Tuple<checkitems, checkitems>>> flatten = null;
flatten = cis =>
    cis
        .Select(x => Tuple.Create(cis, x.Value))
        .Concat(cis.SelectMany(c => flatten(c.Value)));

foreach (var tuple in flatten(root)
    .Where(x => x.Item2.Age > 20)
    .ToArray())
{
    tuple.Item1.Remove(tuple.Item2);
}