Iterating and creating new anonymous types dynamically
I have an anonymous type of this form:
new List<MyList>()
{
new Column { Name = "blah", W开发者_Go百科idth = 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 ... }
}
}
Even with col returning the right sort of data, the above example isn't acceptable and I can't see why.
You try to loop over the collection inside the object initializer block (thx to Luke).
Try creating the list first and than filling it,
var list = new List<MyList>();
foreach (var columns in col)
{
list.Add(new Column { Name = columns.Name ... });
}
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();
maybe something like
var theList = new List<MyList>();
col.ForEach(c=> theList.Add( new Column(){ Name=c.Name ... etc } ));
精彩评论