Sergej Popov
Sergej Popov

Reputation: 3021

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.

Upvotes: 1

Views: 7037

Answers (2)

Parv Sharma
Parv Sharma

Reputation: 12705

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500815

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 (e.g. 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();

Upvotes: 3

Related Questions