gpt4 book ai didi

c# - 遍历 List
转载 作者:太空狗 更新时间:2023-10-30 00:11:24 25 4
gpt4 key购买 nike

如何循环遍历对象类型的列表?

List<object> countries = new List<object>();
countries.Add(new { Name = "United States", Abbr = "US" , Currency = "$"});
countries.Add(new { Name = "Canada", Abbr = "CA", Currency = "$" });
...more

我想在我的 View 中做类似(使用属性名称)的事情

@model ViewModel
@foreach(object country in Model.Countries)
{
Name = country.Name
Code = country.Abbr
Currency = country.Currency
}

更新:忘了说我正在使用 MVC,我想在 View 中循环数据。 Countries 对象是 ViewModel 的属性之一,以查看是强类型的。

更新:根据要求更新以显示如何从 Controller 调用 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);
}

最佳答案

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

关于c# - 遍历 List<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12606061/

25 4 0