如何循环使用Object类型的List?
List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
...more
我想在我的视图中使用(使用属性名称)
@model ViewModel
@foreach(object country in Model.Countries)
{
Name = country.Name
Code = country.Abbr
Currency = country.Currency
}
更新: 忘了提到我正在使用MVC,我想在View中循环数据。 States对象是ViewModel要查看的强类型属性之一。
更新: 按要求更新以显示如何从控制器调用View -
[HttpPost]
public ActionResult Index(FormCollection form)
{
..some validations and some logic
ViewModel myViewModel = new ViewModel();
myViewModel.Countries = GetCountries(); -- this is where data get initialized
myViewModel.Data = db.GetData();
return PartialView("_myPartial", myViewModel);
}
答案 0 :(得分:5)
var countries = new []{
new { Name = "United States", Abbr = "US", Currency = "$" },
new { Name = "Canada", Abbr = "CA", Currency = "$" }
};
foreach(var country in countries)
{
var Name = country.Name;
.....
}
答案 1 :(得分:2)
你也需要让国家匿名。
举个例子,像
var countries = (new[] {
new { Name = "United States", Abbr = "US", Currency = "$" },
new { Name = "Canada", Abbr = "CA", Currency = "$" },
});
List<string> names = new List<string>();
countries.ToList().ForEach(x => { names.Add(x.Name); });
答案 2 :(得分:2)
如果我理解得很好,您正在尝试将视图模型从控制器发送到视图。因此,如果您使用剃刀,您的代码应该是这样的
@model ViewModel
@foreach(object country in Model.countries)
{
var Name = country.Name
var Code = country.Abbr
var Currency = country.Currency
}
注意关键字Model
。
编辑
// Code inside your controller should be like this
ViewModel myModel = new ViewModel();
List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
myModel.countries = countries;
return View("yourView", myModel); // you can write just return View(myModel); if your view's name is the same as your action
希望它对你有所帮助。
答案 3 :(得分:1)
我只想创建一个新类,并使用它而不是通用对象。是否有理由需要使用基础对象?如果需要更多抽象,您可以使用带有Where子句的匿名类型或使用抽象类。
答案 4 :(得分:1)
您定义对象的方式将dynamic
作为唯一选项:两个匿名类的类型不同。你应该写
foreach (dynamic country in countries) {
...
}
或使用命名类的实例初始化您的列表(这是首选,因为在您的情况下dynamic
可能过重)。
答案 5 :(得分:0)
如果你想以某种方式处理多态项(而不是匿名类型),请看一下Cast&lt; ...&gt; .ToList()或OfType&lt; ...&gt; .ToList()