views:

802

answers:

4

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.

+4  A: 

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.

Jon Skeet
+1  A: 

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.

Joel Coehoorn
A: 

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.

Nair
Joel Coehoorn
A: 

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