开发者

Linq query convert to List<string>

开发者 https://www.devze.com 2023-02-10 17:05 出处:网络
I have this code List<string> IDs = new List<string>(); XDocument doc = XDocument.Parse(xmlFile);

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开发者_JAVA百科">
  <a>
    <b>
      <val>other data</val>
    </b>
    <b>

      <val>other data</val>
    </b>
  </a>
</aBase>


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()


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号