I would do this to create the dictionary:
var queryData = query.ToDictionary(x => x.Name.ToString(), x => x.Value);
However, that's only safe if you know your XML doesn't have any duplicate names. If it might have duplicate names, you may want to get a distinct list in your query, or else investigate ToLookup()
as an alternative to ToDictionary()
.
Also, your code is storing the tag name as the dictionary key. If that's what you need, then great. But if you actually need the value of a tag attribute or something like that, then you'll need to change your code.
Update
I think I see what the problem is. You never actually stated what your difficulty in iterating the results is, but I think this might be it:
The Elements()
method returns an IEnumerable<XElement>
. That means that the type of your query
variable is actually IEnumerable<IEnumerable<XElement>>
. If you want to flatten that down to a single list of all the elements, here's how:
var flattened = query.SelectMany(x => x);