简体   繁体   中英

Linq query on XML to Select multiple elements of subnodes

I want to select all distinct values of child from following xml

<root>
  <parent>
    <child>value 1</child>
    <child>value 2</child>
  </parent>
  <parent>
    <child>value 1</child>
    <child>value 4</child>
  </parent>
</root>

I tried following:

var vals  = (from res in XmlResources.Elements("root").Elements("parent") select res)
                                        .SelectMany(r => r.Elements("child")).Distinct().ToList();

But can't get the value from it, gives me value wrapped in tag and not Distinct

Is it possible to show both ways to get it - query and chaining aka lambda.

You're selecting the elements, and the elements are all distinct. You need to get the distinct values . For example:

var values = XmlResources.Element("root")
                         .Elements("parent")
                         .Elements("child")
                         .Select(x => x.Value)
                         .Distinct();

There's really no benefit in using a query expression here - it only adds cruft. I only use a query expression when the query has multiple aspects to it (eg a where and a meaningful select, or a join). For just a select or just a where it's pretty pointless. So yes, you can use:

var values = (from x in XmlResources.Element("root")
                                    .Elements("parent")
                                    .Elements("child")
              select x.Value).Distinct();

... but why would you? It's a lot less clear IMO.

Note that if you don't care too much about the root/parent/child hierarchy, and are happy to just get all the child descendants, you can use:

var values = XmlResources.Descendants("child")
                         .Select(x => x.Value)
                         .Distinct();

yes it is possible both ways

var doc = new XDocument("your xml string");
var values = (from c in doc.Root.Descendants("child") select c.Value).Distinct();

//chaining style

var values = doc.Root.Descendants("child").Select(c=>c.Value).Distinct();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM