5

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.

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);
}
tereško
  • 58,060
  • 25
  • 98
  • 150
peacefulmember
  • 293
  • 2
  • 5
  • 14
  • you could try the cast to anonymous type here http://stackoverflow.com/questions/1409734/cast-to-anonymous-type – Manatherin Sep 26 '12 at 16:18
  • 11
    Use a real class instead of an anonymous type. – Tim Schmelter Sep 26 '12 at 16:18
  • 1
    Or you could also just use `foreach(dynamic country in countries)` if you're using .net 4.0 but the best way is just to create a class – Manatherin Sep 26 '12 at 16:19
  • In this case you could use http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo.currencysymbol.aspx – BrunoLM Sep 26 '12 at 16:27
  • The alternative way is using reflection as given [here][1] [1]: http://stackoverflow.com/questions/2594527/how-do-i-iterate-over-the-properties-of-an-anonymous-object-in-c – peacefulmember Sep 26 '12 at 18:44
  • possible duplicate of [Accessing C# Anonymous Type Objects](http://stackoverflow.com/questions/713521/accessing-c-sharp-anonymous-type-objects) – nawfal Jun 28 '14 at 08:30

6 Answers6

9
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;
      .....
}
L.B
  • 114,136
  • 19
  • 178
  • 224
3

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); });
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
3

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.

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.

kbaccouche
  • 4,575
  • 11
  • 43
  • 65
  • I am not very clear here. Model is referring to ViewModel which has one property as Countries. Then how would it recognize Countries list. I tried your example I get `'object' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'object' could be found.` – peacefulmember Sep 26 '12 at 17:02
  • Can you put the code you are using to call your view from the controller ? – kbaccouche Sep 26 '12 at 17:04
  • You are returning an object when your action should return an ActionResult. Change the return insruction to look like mine and you will be fine ;) – kbaccouche Sep 26 '12 at 17:16
  • Seems like the similar code that I have. I noticed the Model keyword. That is what I have. It was typo in my original question. Sorry about that. – peacefulmember Sep 26 '12 at 17:18
  • - Does it make any difference I return View or PartialView. Please see I corrected my code. – peacefulmember Sep 26 '12 at 17:21
  • not really, but you sure the property is right because I see sometimes you write Countries with capital C and sometimes without – kbaccouche Sep 26 '12 at 17:24
  • Yes - property is right. I am using capital C . It is recognized in my View no error in Foreach statement. its the next statement when reading the properties of Countries. – peacefulmember Sep 26 '12 at 17:27
  • This method GetCountries(); does not take any argument, how are you filling in the property Name ? – kbaccouche Sep 26 '12 at 17:30
  • it initializes countries data as I have posted and returns the type of List. – peacefulmember Sep 26 '12 at 17:32
  • 1
    So the problem is related to using the type Object, try to create your own class Country wich has all the properties you need ("Name" ...) – kbaccouche Sep 26 '12 at 17:51
1

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.

Chris Knight
  • 1,448
  • 1
  • 15
  • 21
1

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

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

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    +1 because you're right, but `dynamic` is not a keyword to use lightly. The OP should probably just define a simple struct type for countries. – KeithS Sep 26 '12 at 16:24
0

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

ranieuwe
  • 2,268
  • 1
  • 24
  • 30