Looping through dictionary object

前端 未结 4 1759
悲哀的现实
悲哀的现实 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<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.

    0 讨论(0)
  • 2020-12-14 15:33
    public class TestModels
    {
        public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
    
        public TestModels()
        {
            sp.Add(0, new {name="Test One", age=5});
            sp.Add(1, new {name="Test Two", age=7});
        }
    }
    
    0 讨论(0)
  • 2020-12-14 15:37

    You can do it like this.

    Models.TestModels obj = new Models.TestModels();
    foreach (var item in obj.sp)
    {
        Console.Write(item.Key);
        Console.Write(item.Value.name);
        Console.Write(item.Value.age);
    }
    

    The problem you most likely have right now is that the collection is private. If you add public to the beginning of this line

    Dictionary<int, dynamic> sp = new Dictionary<int, dynamic> 
    

    You should be able to access it from the function inside your controller.

    Edit: Adding functional example of the full TestModels implementation.

    Your TestModels class should look something like this.

    public class TestModels
    {
        public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
    
        public TestModels()
        {
            sp.Add(0, new {name="Test One", age=5});
            sp.Add(1, new {name="Test Two", age=7});
        }
    }
    

    You probably want to read up on the dynamic keyword as well.

    0 讨论(0)
  • 2020-12-14 15:41

    It depends on what you are after in the Dictionary

    Models.TestModels obj = new Models.TestModels();
    
    foreach (var keyValuPair in obj.sp)
    {
        // KeyValuePair<int, dynamic>
    }
    
    foreach (var key in obj.sp.Keys)
    {
         // Int 
    }
    
    foreach (var value in obj.sp.Values)
    {
        // dynamic
    }
    
    0 讨论(0)
提交回复
热议问题