tags:

views:

54

answers:

1

This is my idea for the code (can the Linq query populate the dictionary object directly?).

XElement doc = XElement.Load(data.xml);
string Element = "KeyNode";
string SearchString = "Dominion";
Dictionary<string, string> QueryData = new Dictionary<string, string>();

var query = from child in doc.Descendants(Element)
            where SearchString == child.Value
            select pn.Parent.Elements();


foreach(XElement x in query)
{
    QueryData.Add(x.Name.ToString(),x.Value);
}
+1  A: 

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);
Joel Mueller
thanks for the dictionary part but to try it I need to iterate the initial result.
Zion
That's it! the rebels are there and I'm sure Skywalker is with them!Thanks a lot, the flattening did the trick. If you can please explain why my resultset yielded nested ienumerables?
Zion
Pretend your select statement was `select child.Name.ToString()`. You'd get an `IEnumerable<string>`. Your real select statement returns a sequence of elements (all the parent's children). Since the end result of a query is a sequence of the values produced by each call to the select statement, and each select statement returns a sequence of elements, you end up with a sequence of a sequence of elements.
Joel Mueller