Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query convert 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 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>
like image 507
Saint Avatar asked Feb 14 '11 23:02

Saint


2 Answers

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()
like image 57
Yuriy Faktorovich Avatar answered Sep 19 '22 15:09

Yuriy Faktorovich


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();
like image 27
Ani Avatar answered Sep 19 '22 15:09

Ani