[英]Recursion for nested Dictionary
I have a dictionary with multiples values.我有一个包含多个值的字典。 My dictionary is as:
我的字典是这样的:
public class checkitems: Dictionary<int, checkitems>{
// ....
}
I am looping over each level like 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 i am writing foreach for each level and checking to see if it satisfies the condition and then adding it to the list to remove.目前我正在为每个级别编写 foreach 并检查它是否满足条件,然后将其添加到列表中以删除。 I wanted to know how would i write it recursively so that i wouldn't have to worry about how much deep the 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 my best in understanding what your code is trying to achieve.我尽力理解您的代码试图实现的目标。 Hope this 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 to the deepest level
foreach (Int32 key in items.Keys)
{
RecurseCheckitems(items[key]);
}
// Step 2: Extract all KEYS of Childelements having an AGE of at least 20
foreach (Int32 key in items.Keys)
{
l_deleteKeys.AddRange(DoCheckItems(items[key]));
}
// Step 3: Remove all extracted keys from the current Objecct
foreach (Int32 deleteKey in l_deleteKeys)
{
items.Remove(deleteKey);
}
}
/// <summary>
/// Helper-Function to extract the keys of Child-Elements having an age of at least 20
/// </summary>
/// <param name="item">Parent-Item to check</param>
/// <returns>List of KEYS of Child-Elements having an Age of at 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; }
}
}
Given a root
instance of checkitems
, try this:给定
checkitems
的root
实例,试试这个:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.