Is it possible to get other collection than IEnumerable<T> when using LINQ: XML to object?
So I have this huge XML file that I am converting to an object by using LINQ. And currently I am doing:
var resultStories = from story in resultXML.Descendants("story")
select new NewsStory
{
ArticleFrequency = from tag in story.Descendants("tag")
select new KeyValuePair<string,int>((string)tag.Element("name"),(int)tag.Element("count"))
};
Now this gives creates a IEnumerable<KeyValuePair<String,int>>
for me. But I am wondering if it is possible to get another collection such as a Dictionary<String,int>
or List<new MyItem(string key, int value)
?
开发者_如何学CI have this huge LINQ book and it only contains information about Objects to XML.
This question pertains XML to Objects.Thank you :)
Yes this is possible using Linqs ToDictionary method.
You should be able to say
ArticleFrequency = (from tag in story.Descendants("tag")
select new
{
Key = (string)tag.Element("name"),
Value = (int)tag.Element("count")
}).ToDictionary(val => val.Key, val => val.Value)
Your ArticleFrequency
property will of course need to be of type IDictionary<string, int>
UPDATE To answer your question in the comments (if I understand correctly), just change the Select to return an Enumerable of the desired type e.g.
ArticleFrequency = (from tag in story.Descendants("tag")
select new MyCustomObject()
{
MyPropertyOne = (string)tag.Element("name"),
MyPropertyTwo = (int)tag.Element("count")
})
will assign an IEnumerable<MyCustomObject>
to ArticleFrequency. If you are saying you want ArticleFrequency to be of type Stack you can just wrap the whole Linq query and use it as the IEnumerable parameter to the Stack constructor overload e.g.
ArticleFrequency = new Stack<KeyValuePair<string, int>>(
(from tag in story.Descendants("tag")
select new KeyValuePair<string, int>()
{
Key = (string)tag.Element("name"),
Value = (int)tag.Element("count")
}))
You can get it to return a Dictionary like so:
ArticleFrequency = story.Descendants("tag").ToDictionary<XElement, string,int>()(
tag=>(string)tag.Element("name"),
tag=>(int)tag.Element("count")
);
精彩评论