问题描述
我很新的.NET用来在PHP中工作
I am very new to .net used to working in PHP
不过,我需要的foreach通过对象字典
However I need to foreach through a dictionary of objects
我的设置是一个MVC4应用
My setup is an MVC4 app
模型看起来像这样
public class TestModels
{
Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>
{
{1, new {name="abc", age="1"}}
{2, new {name="def", age="2"}}
}
控制器
public class TestController : Controller
{
Models.TestModels obj = new Models.TestModels();
}
我如何通过obj的对象循环和检索字典的值,并在视图中打印出来。
How do I loop through the obj object and retrieve the values of the dictionary and print them in the view.
推荐答案
一种方法是通过字典的键,我建议循环:
One way is to loop through the keys of the dictionary, which I recommend:
foreach(var key in sp.Keys)
var value = sp[key];
另一种方式,是遍历字典作为一个序列对的:
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(var pair in sp)
{
var key = pair.Key;
var value = pair.Value;
}
我推荐的第一种方法,因为你可以有更多的控制权,如果你装点键
属性适当的LINQ语句,获取项目的顺序,例如, sp.Keys.OrderBy(X =&GT; X)。
帮助您检索键的升序排列的项目
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.
这篇关于通过字典对象循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!