views:

272

answers:

3

I have an anonymous type of this form:

new List<MyList>()
 {
   new Column { Name="blah", Width=100, Hidden=true },
   new Column { Name="blah1", Width=60, Hidden=false }
 }

How can I go about creating the content within the list dynamically, like:

new List<MyList>()
 {
   foreach (var columns in col) {
      new Column { Name=columns.Name ... etc }
   }
 }

Even with col returning the right sort of data, the above example isn't acceptable and I can't see why.

+1  A: 

maybe something like

var theList = new List<MyList>();
col.ForEach(c=> theList.Add( new Column(){ Name=c.Name ... etc } ));
John Boker
+2  A: 

Not sure exactly what you're asking, but have you tried something of the form:

col.Select(c => new Column {Name = c.Name ... etc}).ToList();
Dave Markle
I thought this was what the poster was asking at first, but I think BeowulfOFs answer may be what Rio is looking for.
Dolphin
+6  A: 

You try to loop over the collection inside the object initializer block (thx to Luke).

Try creating the list first and than filling it,

List<MyList> list = new List<MyList>();
foreach (var columns in col) 
{
    list.Add(new Column { Name=columns.Name ... etc });
}
BeowulfOF
Thank you for a quick response. It looks like it works!
Rio
+1, but with a small nitpick: The code in the question isn't looping "inside the list constructor", it's looping inside an *object initializer* block. http://msdn.microsoft.com/en-us/library/bb384062.aspx
LukeH
@Luke, you're right, i'll correct this.
BeowulfOF