AndrewC
AndrewC

Reputation: 6730

Taking 2 attributes from XElement to create a dictionary LINQ

I'm trying to take one attribute to use as the key, and another to use as the value. If I use (xDoc is an XDocument object in the example):

Dictionary<string, XElement> test = xDoc.Descendants()
    .Where<XElement>(t => t.Name == "someelement")
    .ToDictionary<XElement, string>(t => t.Attribute("myattr").Value.ToString());

I get a dictionary with the myattr value as key (which is what I want) but the entire XElement object as the value.

What I want to do, is to select a second attribute to set as the value property on each dictionary item, but can't seem to figure that out.

Is it possible to do all of this in 1 Linq statement? Curiousity has caught me!

Cheers!

Upvotes: 1

Views: 2185

Answers (2)

48klocs
48klocs

Reputation: 6103

The casting in your .ToDictionary() call flips the parameters around from your object definition.

All you have to do is drop it and add an identity select and it should work.

Dictionary<string, XElement> test = xDoc.Descendants()
            .Where<XElement>(t => t.Name == "someelement")
            .ToDictionary(t => t.Attribute("myattr").Value.ToString(), t => t);

Upvotes: 1

driis
driis

Reputation: 164331

Yes, you can pass in another expression to select the value you want:

Dictionary<string,string> test = xDoc.Descendants()
    .Where(t => t.Name == "someelement")
    .ToDictionary(
        t => t.Attribute("myattr").Value.ToString(), 
        t => t.Attribute("otherAttribute").Value.ToString());

Upvotes: 4

Related Questions