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.
Edit: I've tried to implement Spender's solution solution below but I'm having difficulty understanding what I need to change in my code. Can somebody clarify? Thanks