c# - Recursion for nested Dictionary -


i have dictionary multiples values. dictionary as:

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

i looping on each level this.

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)         }     } } 

currently writing foreach each level , checking see if satisfies condition , adding list remove. wanted know how write recursively wouldn't have worry how deep levels go.

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 

i did best in understanding code trying achieve. hope helps

using system; using system.collections.generic;  namespace consoleapplication2 {     public static class program     {         public static void recursecheckitems(checkitems items)         {             list<int32> l_deletekeys = new list<int32>();              // step 1: dfs - down down down deepest level             foreach (int32 key in items.keys)             {                 recursecheckitems(items[key]);             }              // step 2: extract keys of childelements having age of @ least 20             foreach (int32 key in items.keys)             {                 l_deletekeys.addrange(docheckitems(items[key]));             }              // step 3: remove extracted keys current objecct             foreach (int32 deletekey in l_deletekeys)             {                 items.remove(deletekey);             }         }          /// <summary>         /// helper-function extract keys of child-elements having age of @ least 20         /// </summary>         /// <param name="item">parent-item check</param>         /// <returns>list of keys of child-elements having age of @ least 20</returns>         private static list<int32> docheckitems(checkitems item)         {             list<int32> l = new list<int32>();              foreach (int32 key in item.keys)             {                 if (item[key].age > 20)                 {                     l.add(key);                 }             }              return l;         }     }      public sealed class checkitems : dictionary<int32, checkitems>     {         public int32 age { get; set; }     } } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -