'How can I go through different levels in a dictionary
I've been reading a lot of documentation on how to iterate a Dictionary with a foreach, but I don't quite understand how I can go through the levels it has. For example:
I have "params" Dictionary, I add string and object values to it, with .Add(), and to one of them I add a level called "item".
From what I understand, with the Foreach(KeyValueaPair<>) it is to iterate through the Dictionary. Do I need to use another foreach(KeyValuePair<>) to be able to loop through the second level?
For example, I want "param" to get the value of the element that Posnr brings
IDictionary<string, object> params = new Dictionary<string, object>();
params.Add("Customerid", zwCustomer.Customerid);
params.Add("PedidoCli", zwCustomer.PedidoCli);
params.Add("PedidoSap", zwCustomer.PedidoSap);
params.Add("TFacturaMat", new Dictionary<string, object>()
{
{
"item", new Dictionary<string, object>()
{
{"Vbeln", zfacturaMats.Vbeln},
{"Posnr", zfacturaMats.Posnr},
{"Matnr", zfacturaMats.Matnr},
}
},
});
foreach(KeyValuePair<string, object> item in parametros)
{
param = $"{item.Key} : {item.Value}";
}
Solution 1:[1]
No, you can do that directly. The Dictionary<TKey, TValue> class of the .NET library already does all that magic for you.
With the foreach loop
foreach(KeyValuePair<string, object> item in params)
{
Console.WriteLine($"{item.Key} : {item.Value}");
}
you already iterate trough all the elements of your dictionary. From an usage point of view this works exactly the same as if params was a List (except that there's no guaranteed order).
If you want a particular element, you have multiple possibilities, but in the easiest case you can just get an element by var myValue = params["PosNr"]. Alternatively you can use the TryGetValue() method to test whether a certain key is present.
So bottom line: It's interesting to know how a dictionary works internally, but when you use the .NET libraries, you don't have to care about that. Iterating and accessing works just out of the box.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PMF |
