Nair
Nair

Reputation: 7458

how to use foreach in linq

I have read in some blog some time ago (sorry for being vague) that i could use a linq like the following

var list = from c in xml
           select new 
           {
              foreach(XElement el in c.Elements())
              {
              }
           }

Does anyone know is it possible or is it just my imagination??

Thanks.

Upvotes: 1

Views: 4522

Answers (4)

JustEngland
JustEngland

Reputation: 1390

You can use the ToList() function to convert the elements to a list of List then you can use the ForEach Method on it. FYI when using LinqToXml I find the Descendants() more useful as it will do a full dive into the object model.

xml.Elements().ToList().ForEach(ele => DoSomething(ele));

Upvotes: 2

Nair
Nair

Reputation: 7458

Ok, I have an xml with two parts, first declares the fields in the xml and second part has data associated with the declaration in the first part. So what I am trying to do is, read the first of the field definition and use that to create anonymous class of the data in the second section. Trying not to hard code in the program since we get data from different sources with different field definitions.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

It's your imagination. You can use the results of a linq query in a foreach loop, but you can't use a foreach loop like that in the declaration for an anonymous type.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503799

You can't use a foreach loop directly in an anonymous type initialization expression, no.

If you could tell us what you're trying to achieve, we could probably help you find the best way of doing it.

Upvotes: 4

Related Questions