C# 遍历 List<object>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12606061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:52:21  来源:igfitidea点击:

iterate through List<object>

c#asp.net-mvc

提问by peacefulmember

How can I loop through a List of type Object?

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

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

I want to do something like (using property names) in my view

我想在我看来做一些类似(使用属性名称)的事情

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

UPDATE: Forgot to mention that I am using MVC and I want to loop the data in View. Countries object is one of the property of ViewModel to view is strongly typed.

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

UPDATE: updating as asked to show how View is called from the controller -

更新:按要求更新以显示如何从控制器调用视图 -

[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);
}

采纳答案by kbaccouche

If I understood well, you are trying to send the view model from the controller to the view. So if you are using razor your code should be like this

如果我理解得很好,您正在尝试将视图模型从控制器发送到视图。所以如果你使用剃刀你的代码应该是这样的

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

notice the keyword Model.

注意关键字Model

Edit

编辑

// 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 

Hope it helps you.

希望对你有帮助。

回答by Adriaan Stander

You need to make countries anonymous too.

你也需要让国家匿名。

As an exaplme, something like

作为一个例子,像

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

回答by Chris Knight

I would just create a new class, and use that instead of the generic object. Is there a reason that it needs to use the base level object? If more abstraction is needed you could utilize an anonymous type with a Where clause or use an abstract class.

我只想创建一个新类,并使用它而不是通用对象。是否有理由需要使用基本级别的对象?如果需要更多抽象,您可以使用带有 Where 子句的匿名类型或使用抽象类。

回答by dasblinkenlight

The way you defined your objects leaves dynamicas your only option: the two anonymous classes are of different type. You should either write

您定义对象的方式dynamic是您唯一的选择:两个匿名类的类型不同。你应该写

foreach (dynamic country in countries) {
    ...
}

or initialize your list with instances of a named class (this is preferred, because dynamicmay be too heavy in your situation).

或使用命名类的实例初始化您的列表(这是首选,因为dynamic在您的情况下可能太重了)。

回答by ranieuwe

If you want to work with the polymorphic items somehow (and not with anonymous types) take a look at Cast<...>.ToList() or OfType<...>.ToList()

如果您想以某种方式使用多态项(而不是匿名类型),请查看 Cast<...>.ToList() 或 OfType<...>.ToList()

回答by L.B

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