LINQ to XML - How to get Dictionary from Anonymous Object?
Posted
by DaveDev
on Stack Overflow
See other posts from Stack Overflow
or by DaveDev
Published on 2010-04-28T22:42:25Z
Indexed on
2010/04/30
8:17 UTC
Read the original article
Hit count: 206
Currently I'm getting a list of HeaderColumns from the following XML snippet:
<PerformancePanel>
<HeaderColumns>
<column performanceId="12" text="Over last month %" />
<column performanceId="13" text="Over last 3 months %" />
<column performanceId="16" text="1 Year %" />
<column performanceId="18" text="3 Years % p.a." />
<column performanceId="20" text="5 Years % p.a." />
<column performanceId="22" text="10 Years % p.a." />
</HeaderColumns>
</PerformancePanel>
from which I create an object as follows: (admitedly similar to an earlier question!)
var performancePanels = new
{
Panels = (from panel in doc.Elements("PerformancePanel")
select new
{
HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column")
select new
{
PerformanceId = (int)column.Attribute("performanceId"),
Text = (string)column.Attribute("text")
}).ToList(),
}).ToList()
};
I'd like if HeaderColumns was a Dictionary() so later I extract the values from the anonymous object like follows:
Dictionary<int, string> myHeaders = new Dictionary<int, string>();
foreach (var column in performancePanels.Panels[0].HeaderColumns)
{
myHeaders.Add(column.PerformanceId, column.Text);
}
I thought I could achieve this with the Linq to XML with something similar to this
HeaderColumns = (from column in panel.Elements("HeaderColumns").Elements("column")
select new Dictionary<int, string>()
{
(int)column.Attribute("performanceId"),
(string)column.Attribute("text")
}).ToDictionary<int,string>(),
but this doesn't work because
- ToDictionary() needs a Func parameter and I don't know what that is / how to implement it, and
- the code's probably wrong anyway!
Could somebody please suggest how I can achieve the result I need? Thanks.
© Stack Overflow or respective owner