Update inner Dictionary as Value in outer Dictionary - c#

In such a construction:
Dictionary<myObject, Dictionary<myEnum, secondObject>> myDict;
I use foreach to search all items in outer Dictionary:
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
}
How to do this?

The foreach loop on a Dictionary enumerates key-value pairs. The key is in elem.Key; the value (i.e. your target inner dictionary) is elem.Value.
foreach (var elem in myDict)
{
//I need to make some modifications in inner Dictionary for chosen myEnum
Dictionary<myEnum, secondObject> inner = elem.Value;
inner[myEnum.EnumVal1] = new secondObject(123);
inner[myEnum.EnumVal2] = new secondObject(456);
}

You were close, it seems you just have some confusion over getting access to the inner dictionary?
foreach (var elem in myDict) // var is KeyValuePair<myObject, Dictionary<myEnum, secondObject>>
{
var innerDict = elem.Value; // Value is Dictionary<myEnum, secondObject>
if (innerDict != null)
{
if (innerDict.ContainsKey(enumVal)) // key is myEnum
{
var value = innerDict[enumVal]; // var is secondObject
}
}
}

Since no details is given about myObject or secondObject the following may be too generic but at least may give you an idea:
foreach (var elem in myDict)
{
var temp = elem.Value.Single(p => p.Key == MyEnum.a);
(temp.Value as MySecondObject).anyProperty = anyValue;
}

Related

How to iterate over nested dictionaries in c# recursively

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

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

foreach items in hashtable

I need to use Hastable (Not List and not Dictionary), and I have many variables with keys. I add keys and variables to class, and use it in my program. But I don't know how to parse Hashtable. I tried this:
Hashtable toboofer = null;
string path = #"my.bin";
FileStream fin = File.OpenRead(path);
try
{
BinaryFormatter bf = new BinaryFormatter();
toboofer = (Hashtable)bf.Deserialize(fin);
for (int i = 0; i <= toboofer.Count; i++ )
//foreach (KeyValuePair<string, string> kvp in toboofer)
{
myclass cl = new myclass();
cl.Fio = toboofer[i].ToString();
cl.About = toboofer[i].ToString();
}
}
but I have an error. When I try string item or cycle for I have an error too.
Hashtable has DictionaryEntry as collection element
foreach (DictionaryEntry entry in toboofer)
{
// do something
}
Make list of myclass from hashtable:
var listOfMyClass = toboofer.Cast<DictionaryEntry>().
Select(e => new myclass()
{ Fio = e.Key.ToString(), About = e.Value.ToString() });
try this hashtable make use if DictionaryEntry, where KeyValuePair generic used by generic dictionary .Net 2 (and onwards)
Aslo note that Hashtable doesnt have generic version of it and Each element in hastable represented by DictionaryEntry
foreach (DictionaryEntry entry in hashtable)
{
Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

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

using a for loop to iterate through a dictionary

I generally use a foreach loop to iterate through Dictionary.
Dictionary<string, string> dictSummary = new Dictionary<string, string>();
In this case I want to trim the entries of white space and the foreach loop does however not allow for this.
foreach (var kvp in dictSummary)
{
kvp.Value = kvp.Value.Trim();
}
How can I do this with a for loop?
for (int i = dictSummary.Count - 1; i >= 0; i--)
{
}
what about this?
for (int i = dictSummary.Count - 1; i >= 0; i--) {
var item = dictSummary.ElementAt(i);
var itemKey = item.Key;
var itemValue = item.Value;
}
KeyValuePair<TKey, TValue> doesn't allow you to set the Value, it is immutable.
You will have to do it like this:
foreach(var kvp in dictSummary.ToArray())
dictSummary[kvp.Key] = kvp.Value.Trim();
The important part here is the ToArray. That will copy the Dictionary into an array, so changing the dictionary inside the foreach will not throw an InvalidOperationException.
An alternative approach would use LINQ's ToDictionary method:
dictSummary = dictSummary.ToDictionary(x => x.Key, x => x.Value.Trim());
You don't need to use .ToArray() or .ElementAt(). It is as simple as accessing the dictionary with the key:
dictSummary.Keys.ToList().ForEach(k => dictSummary[k] = dictSummary[k].Trim());

Categories