Looping through dictionary object

前端 未结 4 1762
悲哀的现实
悲哀的现实 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: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 sp = new Dictionary 
    

    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 sp = new Dictionary();
    
        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.

提交回复
热议问题