【发布时间】:2009-08-26 11:50:03
【问题描述】:
在previous question 中,我询问了如何对 XML 元素进行逻辑分组,我得到了答案,即嵌套 Linq 查询。
问题是,这具有左连接嵌套查询的效果。例如,假设我想列出美国所有以字母“Y”开头的城市,按州和县分组:
XElement xml = new XElement("States",
from s in LinqUtils.GetTable<State>()
orderby s.Code
select new XElement("State",
new XAttribute("Code", s.Code),
new XAttribute("Name", s.Name),
from cy in s.Counties
orderby cy.Name
select new XElement("County",
new XAttribute("Name", cy.Name),
from c in cy.Cities
where c.Name.StartsWith("Y")
orderby c.Name
select new XElement("City",
new XAttribute("Name", c.Name)
)
)
)
);
Console.WriteLine(xml);
这个输出:
<States>
<State Code="AK" Name="Alaska ">
<County Name="ALEUTIANS EAST" />
<County Name="ALEUTIANS WEST" />
<County Name="ANCHORAGE" />
<County Name="BETHEL" />
...
<County Name="YAKUTAT">
<City Name="YAKUTAT" />
</County>
<County Name="YUKON KOYUKUK" />
</State>
<State Code="AL" Name="Alabama ">
<County Name="AUTAUGA" />
...
etc.
我不想要左连接效果;我只想查看实际包含以字母“Y”开头的城市的州和县。
我可以想到几种方法来做到这一点,但它们都显得笨拙和不雅。你能想到的最简洁的方法是什么来达到预期的效果?
【问题讨论】:
标签: c# xml linq linq-to-xml