Looping through dictionary object

前端 未结 4 1763
悲哀的现实
悲哀的现实 2020-12-14 14:51

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 l

4条回答
  •  爱一瞬间的悲伤
    2020-12-14 15:17

    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 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.

提交回复
热议问题