【发布时间】:2010-06-11 09:27:55
【问题描述】:
我有以下 XML:
<PerformancePanel page="PerformancePanel.ascx" title="">
<FundGroup heading="Net Life Managed Funds">
<fund id="17" countryid="N0" index="24103723" />
<fund id="81" countryid="N0" index="24103723" />
<fund id="127" countryid="N0" index="24103722" />
<fund id="345" countryid="N0" index="24103723" />
<fund id="346" countryid="N0" index="24103723" />
</FundGroup>
<FundGroup heading="Net Life Specialist Funds">
<fund id="110" countryid="N0" index="24103717" />
<fund id="150" countryid="N0" index="24103719" />
<fund id="119" countryid="N0" index="24103720" />
<fund id="115" countryid="N0" index="24103727" />
<fund id="141" countryid="N0" index="24103711" />
<fund id="137" countryid="N0" />
<fund id="146" countryid="N0" />
<fund id="133" countryid="N0" />
<fund id="90" countryid="N0" />
<fund id="104" countryid="N0" />
<fund id="96" countryid="N0" />
</FundGroup>
</PerformancePanel>
我可以将数据放入匿名对象中,如下所示:
var offlineFactsheet = new
{
PerformancePanels =
(from panel in doc.Elements("PerformancePanel")
select new PerformancePanel
{
PerformanceFunds = (from fg in panel.Elements("FundGroup")
select new
{
Heading = (fg.Attribute("heading") == null)
? ""
: (string)fg.Attribute("heading"),
Funds =
(from fund in fg.Elements("fund")
select new Fund
{
FundId = (int)fund.Attribute("id"),
CountryId = (string)fund.Attribute("countryid"),
FundIndex = (fund.Attribute("index") == null)
? null
: new Index
{
Id = (int)fund.Attribute("index")
},
FundNameAppend = (fund.Attribute("append") == null)
? ""
: (string)fund.Attribute("append")
}).ToList()
}).ToDictionary(xx => xx.Heading, xx => xx.Funds)};
我正在尝试更改我的代码,以便我可以将字典直接分配给我正在使用的类的属性,如this question 中所述。 我想要一个 Dictionary() ,其中每个标题文本都是它下面的资金列表的关键。我在链接问题中应用示例时遇到困难,因为它只返回一个字符串,而这需要返回字典。
这是在我意识到自己迷路之前就已经到达的点了!!!:
this.PerformancePanels = doc.Elements("PerformancePanel").Select(e =>
{
var control = (PerformancePanel)LoadControl(this.OfflineFactsheetPath
+ (string)e.Attribute("page"));
control.PerformanceFunds = e.Elements("FundGroup").Select(f =>
{
List<Fund> funds = (from fund in e.Elements("fund")
select new Fund
{
FundId = (int)fund.Attribute("id"),
CountryId = (string)fund.Attribute("countryid"),
FundIndex = (fund.Attribute("index") == null)
? null
: new Index
{
Id = (int)fund.Attribute("index")
},
FundNameAppend = (fund.Attribute("append") == null)
? ""
: (string)fund.Attribute("append")
}).ToList();
string heading = (e.Attribute("heading") == null)
? ""
: (string)e.Attribute("heading");
}).ToDictionary(xx => heading, xx => Funds);
return control;
}).ToList();
有人能指出我正确的方向吗?我什至不确定“表达”是否是正确的术语。有人也可以填写我吗?谢谢。
【问题讨论】:
标签: c# linq-to-xml lambda