I am very new to .NET, used to working in PHP. I need to iterate via foreach
through a dictionary of objects. My setup is an MVC4 app.
The Model looks like this:
public class TestModels { Dictionary<int, dynamic> sp = new Dictionary<int, dynamic> { {1, new {name="abc", age="1"}}, {2, new {name="def", age="2"}} } }
Controller:
public class TestController : Controller { Models.TestModels obj = new Models.TestModels(); }
How do I loop through the obj
object and retrieve the values of the dictionary and print them in the view?
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Using Keys() Method To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.
filter() is another built-in function that you can use to iterate through a dictionary in Python and filter out some of its items. This function is defined as filter(function, iterable) and returns an iterator from those elements of iterable for which function returns True .
One way is to loop through the keys of the dictionary, which I recommend:
foreach(int key in sp.Keys) dynamic value = sp[key];
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(KeyValuePair<int, dynamic> pair in sp) { int key = pair.Key; dynamic value = pair.Value; }
I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys
property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)
helps you retrieve the items in ascending order of the key. Note that Dictionary
uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.
Update (01 Dec 2016): replaced var
s with actual types to make the answer more clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With