2

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

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

0

3 Answers 3

7

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 ... });
}
Sign up to request clarification or add additional context in comments.

1 Comment

+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. msdn.microsoft.com/en-us/library/bb384062.aspx
2

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

1 Comment

I thought this was what the poster was asking at first, but I think BeowulfOFs answer may be what Rio is looking for.
1

maybe something like

var theList = new List<MyList>();
col.ForEach(c=> theList.Add( new Column(){ Name=c.Name ... etc } ));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.