How to iterate over nested dictionaries in c# recursively - c#

I have dictionary variable is like:
Dictionary<string,object> dictionary;
This dictionary has nested dictionaries inside in runtime like:
Dictionary<string,Dictionary<string,Dictionary<....<Dictionary<string,int>>>
I am trying to search for all the keys in these nested dictionaries. It may be possible with recursive but i coudn't handle the recursive case. After string comparisons(string.Contains("searchText") done i am going to keep only contained ones.
How can i achieve this goal?

You can try dfs.. Below code just prints every key
public void NestedDictIteration(Dictionary<string,object> nestedDict)
{
foreach (string key in nestedDict.Keys)
{
Console.WriteLine(key);
object nextLevel = nestedDict[key];
if(nextLevel == null)
{
continue;
}
NestedDictIteration((Dictionary<string, object>)nextLevel);
}
}

You can do like this.
Dictionary<string, Dictionary<string, string>> dict= new Dictionary<string, Dictionary<string, string>>();
var query = from outer in dict
from inner in outer.Value
select outer.Key + "->>" + inner.Key + ", " + inner.Value;
foreach (string item in query)
{
//item
}
Or like this
foreach (string key in dict.Keys)
{
foreach (string innerKey in dict[key].Keys)
{
//dict[key][innerKey];
}
}

Related

print OrderedDictionary array values?

Line: gets one line from the file, it's iterate
string[] values = line.split(","); // ex: ["hi, "test", "no", "sup"]
OrderedDictionary od = new OrderedDictionary();
Tuple<int, string[]> innerTuple = new Tuple<int, string[]>(int.Parse(value[0], values);
I cannot seem to find a way to print out the value array. However, I can print out the arrays by using regular dictionary (I don't like how dictionary can mix up the order of insertion).
Try with this:
foreach (DictionaryEntry item in od)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
UPDATE:
If you have a string array as the value then you should try something like this:
foreach (DictionaryEntry item in od)
{
if (item.Value is string[])
{
foreach (string str in (string[])item.Value)
{
Console.WriteLine("A string item: " + str);
}
}
}

IDictionary<String, List<OpenXmlCompositeElement>> - get the List<OpenXmlCompositeElement>?

I'm working with Open XML & I have a IDictionary<String, List<OpenXmlCompositeElement>> structure. I want to work with the List part of the structure but this.map.Values tries to wrap it in an ICollection. How can I get the List part from my structure?
public List<OpenXmlCompositeElement> MapData()
{
//this does not work
return this.map.Values;
}
Since it is a dictionary, it expects you to tell from which key you want the value.
So this would be the code you need, where yourKey is the key you want to retrieve:
public List<OpenXmlCompositeElement> MapData()
{
return this.map["yourKey"];
}
If you have no interest in the key, and the dictionary is just a dictionary because the serializer says so, you could get the first item for example like this:
public List<OpenXmlCompositeElement> MapData()
{
return this.map.Values.First();
}
You can either loop through the dictionary and use the value you would like, or access the List directly using the key (in this case it's a string)
IDictionary<String, List<OpenXmlCompositeElement>> myDictionary;
List<OpenXmlCompositeElement> myList = myDictionary["myKey"];
Where myKey is available in the dictionary.
Alternatively you can loop through
foreach (var item in myDictionary)
{
var key = item.Key;
var value = item.Value
// You could then use `key` if you are unsure of what
// items are in the dictionary
}
Assuming this is your dictionary...
IDictionary<string, List<OpenXmlCompositeElement>> items = ...;
Get a specific List by key...
List<OpenXmlCompositeElement> list = items["key"];
Get the first list in the dictionary...
List<OpenXmlCompositeElement> list = items.Values.First();
Concatenate all lists in the dictionary into a single list...
List<OpenXmlCompositeElement> list = items.SelectMany(o => o).ToList();
foreach(KeyValuePair<string, List<OpenXmlCompositeElement>> kvp in IDictionary)
{
string key = kvp.key
List<OpenXmlCompositeElement> list = kvp.Value;
foreach(OpenXmlCompositeElement o in list)
{
Do anything you need to your List here
}
}
I am working with dictionaries as well, so here is a real example that I am currently working with:
foreach(KeyValuePair<string, List<DataRecords>> kvp in vSummaryResults)
{
string sKey = kvp.Key;
List<DataRecords> list = kvp.Value;
string[] vArr = sKey.Split(',');
int iTotalTradedQuant = 0;
double dAvgPrice = 0;
double dSumQuantPrice = 0;
double dQuantPrice = 0;
double dNumClose = 0;
foreach (DataRecords rec in list)
{
if(vSummaryResults.ContainsKey(sKey))
{
iTotalTradedQuant += rec.iQuantity;
dQuantPrice = rec.iQuantity * rec.dInputTradePrice;
dSumQuantPrice += dQuantPrice;
dAvgPrice = dSumQuantPrice / iTotalTradedQuant;
dNumClose = rec.dNumericClosingPrice;
}
else
{
vSummaryResults.Add(sKey, list);
//dNumClose = rec.dNumericClosingPrice;
}

How to retrieve all values in dictionary

I have the following Dictionary
public static Dictionary<string, List<int>> termDocumentIncidenceMatrix = new Dictionary<string, List<int>>();
I want to print all values in it , How i can make it ?
I found KeyValuePair but can't recognize in my program ?
Can anyone give me bit of code or link ?
foreach (var term in termDocumentIncidenceMatrix)
{
// Print the string (your key)
Console.WriteLine(term.Key);
// Print each int in the value
foreach (var i in term.Value)
{
Console.WriteLine(i);
}
}
If you want to print all values of the dictionary, you can use:
Dictionary<string, List<int>> dict = new Dictionary<string,List<int>>{{"A",new List<int>{1,2}},{"B",new List<int>{3,4}}};
var integersList = dict.Values.SelectMany(it => it);
foreach (var item in integersList)
{
Console.WriteLine(item);
}

How to access object in array( Dynamic DataType) with foreach loop in C#

Big Picture
i have this dynamic object. it is an array of object. i want to do a foreach loop in this object array.
i can foreach for a single object like below
foreach (KeyValuePair<dynamic, dynamic> pair in jsonstaticobj1232)
{
dwt.Add(pair.Key, pair.Value);
}
but how to foreach loop in a obj array?
foreach loop for dynamic object in array.
foreach (dynamic dObject in mArray)
{
}
Try this
for(int=0;i<jsonstaticobj1232.Length;i++)
{
foreach (KeyValuePair<dynamic, dynamic> pair in jsonstaticobj1232[i])
{
dwt.Add(pair.Key, pair.Value);
}
}
List<string> layers = new List<string>();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);
foreach (Dictionary<string,dynamic> key in dict["layers"])
{
key.TryGetValue("name", out layersDic);
layers.Add(layersDic);
}

Updating a dictionary dynamically with foreach

When trying to update a Dictionary with the following:
foreach(KeyValuePair<string, string> pair in dict)
{
dict[pair.Key] = "Hello";
}
And exception is thrown. Is there any way to dynamically update the dictionary WITHOUT making any kind of key or value backups?
EDIT!!!!!! View code. I realized that this portion was actually doable. The real case is this. I thought they would be the same, but they are not.
foreach(KeyValuePair<string, string> pair in dict)
{
dict[pair.Key] = pair.Key + dict[pair.Key];
}
Any reason why you're not iterating over the keys?
foreach(var key in dict.Keys)
{
dict[key] = "Hello";
}
You can either loop over the dictionary (you need to use ToList because you can't change a collection that is being looped over in a foreach loop)
foreach(var key in dict.Keys.ToList())
{
dict[key] = "Hello";
}
or you can do it in one line of LINQ as you're setting the same value to all the keys.
dict = dict.ToDictionary(x => x.Key, x => "Hello");
Updated question
foreach (var key in dict.Keys.ToList())
{
dict[key] = key + dict[key];
}
and the LINQ version
dict = dict.ToDictionary(x => x.Key, x => x.Key + x.Value);
If you want to avoid using ToList, you can use ElementAt so that you can modify the collection directly.
for (int i = 0; i < dict.Count; i++)
{
var item = dict.ElementAt(i);
dict[item.Key] = item.Key + item.Value;
}

Categories