Linq query converted to List <string>
I have this code
List<string> IDs = new List<string>();
XDocument doc = XDocument.Parse(xmlFile);
var query = from c in doc.Root.Elements("a").Elements("b")
select new { ID = c.Element("val").Value};
How to convert a query to List without loop foreach?
{ ID = c.Element("val")}
- these, of course, are strings
EDIT
my xml file
<?xml version="1.0" encoding="utf-8"?>
<aBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<a>
<b>
<val>other data</val>
</b>
<b>
<val>other data</val>
</b>
</a>
</aBase>
+5
2 answers
An anonymous type doesn't really help you, since you only need a sequence of strings, not some tuple. Try:
XDocument doc = XDocument.Parse(xmlFile);
var query = from c in doc.Root.Elements("a").Elements("b")
select c.Element("val").Value;
var IDs = query.ToList();
Personally, I would just use the syntax method completely:
var IDs = doc.Root.Elements("a")
.Elements("b")
.Select(c => c.Element("val").Value)
.ToList();
+4