C# linq ToDictionary

K

Keith

Hi

How do I convert to following code to return a Dictionary referenced by the
key?

public List<KeyXpath> GetXPathExpressions()
{
try
{
var results = from xpaths in XDocumentObj.Descendants("value")
select new KeyXpath
{
Key = xpaths.Attribute("key").Value,
Xpath = xpaths.Attribute("xpath").Value
};
return results.ToList();

}
catch
{
return new List<KeyXpath>(0);
}
}

public class KeyXpath
{
public string Key { get; set; }
public string Xpath { get; set; }
}

The Xml file its reading looks like :

<?xml version="1.0" encoding="utf-8" ?>
<DataMining>
<!--
key = this is the value that the component extracting data uses to find the
xpath
xpath = a valid XPath expression to the data in the Xml document
-->
<value key="two" xpath="//one/two"/>
<value key="one" xpath="//three[@four = 'five']" />
</DataMining>

I've been looking around and trying to find a solution for a couple of weeks
now. Its easy to create a dictionary using key that is a property of the
object to be stored in the dictionary but I couldn't adapt this code to work
with a key value string pair.

The function signiture should look like :
public Dictionary<string, string> GetExpressions()

Can someone help me please.

Thanks

K
 
J

Jon Skeet [C# MVP]

How do I convert to following code to return a Dictionary referenced by the
key?

return XDocumentObj.Descendants("value")
.ToDictionary(x => x.Attribute("key").Value, x =>
x.Attribute("xpath").Value);

Jon
 
N

Nicholas Paldino [.NET/C# MVP]

Keith,

I believe that ToDictionary will give you basically a Dictionary<string,
KeyXpath> right?

I would create the query, and then iterate through it yourself to create
the resulting dictionary:

public Dictionary<string, string> GetExpressions()
{
try
{
IEnumerable<KeyXpath> query =
from xpaths in XDocumentObj.Descendants("value")
select new KeyXpath
{ Key = xpaths.Attribute("key").Value, Xpath =
xpaths.Attribute("xpath").Value };

// The return value.
Dictionary<string, string> retVal = new Dictionary<string,
string>();

foreach (KeyXPath item in query)
{
retVal.Add(item.Key, item.Xpath);
}

return retVal;
}
catch
{
return new Dictionary<string, string>();
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Keith,

You should use Jon's solution, it's definitely more elegant, and a lot
less code to maintain.
 
K

Keith

Thanks thats done it perfectly.

Jon Skeet said:
return XDocumentObj.Descendants("value")
.ToDictionary(x => x.Attribute("key").Value, x =>
x.Attribute("xpath").Value);

Jon
 
J

Jon Skeet [C# MVP]

Keith said:
Thanks thats done it perfectly.

It's often worth having a look at the overloads of the standard LINQ
operators. Query expressions are lovely, but they don't let you take
advantage of everything...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top