I have the following code which dynamically selects all of the distinct element names, however; I also want to see the values for these elements. How can I do this using LINQ? I am open to doing it other ways as well.
XDocument doc = XDocument.Load("XMLFile1.xml");
foreach (var name in doc.Descendants("QueryResults").Elements()
.Select(x => x.Name).Distinct())
{
}
Something like this would work
XDocument doc = XDocument.Load("XMLFile1.xml");
foreach (var name in doc.Descendants("QueryResults").Elements()
.Select(x => new {Name = x.Name, Value = e.Value}).Distinct())
{
}
The accepted query is differnt then the original one because it changes how Distinct works because it no longer compares only Name but also Value. If you want to see which names have which values you need to use GroupBy on the Name and get the Value for each item.
var results =
doc
.Descendants("QueryResults")
.Elements()
.GroupBy(x => x.Name, (name, items) => new
{
Name = name,
Values = items.Select(x => x.Value)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With