Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through dictionary object

Tags:

c#

.net

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?

like image 714
user1833222 Avatar asked Feb 06 '13 01:02

user1833222


People also ask

Can you loop through dictionary?

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.

How do I iterate through a dictionary item?

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.

Can you iterate through a dictionary Python?

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 .


1 Answers

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 vars with actual types to make the answer more clear.

like image 62
Sina Iravanian Avatar answered Oct 04 '22 05:10

Sina Iravanian