2009-08-25 57 views
0

好的,我問了如何返回一個Linq查詢結果爲XML,並且我得到了答案hereLinq/XML:在XML元素內正確分組結果

但是有一個小問題:結果不能在邏輯上在XML中分組。例如:

XElement xml = new XElement("States", 
    from s in MyStates 
    from cy in s.Counties 
    from c in cy.Cities 
    where s.Code == "NY" 
    orderby s.Code, cy.Name, c.Name 
    select new XElement("State", 
    new XAttribute("Code", s.Code), 
    new XAttribute("Name", s.Name), 
    new XElement("County", 
     new XAttribute("Name", cy.Name), 
     new XElement("City", 
     new XAttribute("Name", c.Name) 
    ) 
    ) 
) 
); 

Console.WriteLine(xml); 

輸出的形式爲:

<State Code="NY" Name="New York "> 
    <County Name="WYOMING"> 
    <City Name="WARSAW" /> 
    </County> 
</State> 
<State Code="NY" Name="New York "> 
    <County Name="WYOMING"> 
    <City Name="WYOMING" /> 
    </County> 
</State> 
<State Code="NY" Name="New York "> 
    <County Name="YATES"> 
    <City Name="BELLONA" /> 
    </County> 
</State> 
<State Code="NY" Name="New York "> 
    <County Name="YATES"> 
    <City Name="MIDDLESEX" /> 
    </County> 
</State> 
<State Code="NY" Name="New York "> 
    <County Name="YATES"> 
    <City Name="PENN YAN" /> 
    </County> 
</State> 
<State Code="NY" Name="New York "> 
    <County Name="YATES"> 
    <City Name="RUSHVILLE" /> 
    </County> 
</State> 

代替:

<State Code="NY" Name="New York "> 
    <County Name="WYOMING"> 
    <City Name="WARSAW" /> 
    <City Name="WYOMING" /> 
    </County> 
    <County Name="YATES"> 
    <City Name="BELLONA" /> 
    <City Name="MIDDLESEX" /> 
    <City Name="PENN YAN" /> 
    <City Name="RUSHVILLE" /> 
    </County> 
</State> 

如何根據需要我去出現的結果?

回答

1

爲了得到你想要的結果,我相信你必須嵌套LINQ to XML查詢。在外部查詢中,您必須查詢不同的狀態......然後是內部查詢以獲取該州的縣...然後是另一個內部查詢以獲取該縣的城市。