Linq query convert to List<string>
23,590
Solution 1
IDs = query.Select(a => a.ID).ToList();
or if you'd like to do it in one line
List<string> IDs = (from c in doc.Root.Elements("a").Elements("b")
select c.Element("val").Value).ToList()
Solution 2
The anonymous type isn't really helping you since you only need a sequence of strings, not any sort of 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 method-syntax all the way:
var IDs = doc.Root.Elements("a")
.Elements("b")
.Select(c => c.Element("val").Value)
.ToList();
Author by
Saint
Updated on February 15, 2020Comments
-
Saint over 4 years
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 can I convert query to List without loop foreach ?
{ ID = c.Element("val")}
are strings of course
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>