我試圖將我的頭圍繞Linq轉換爲XML。我有一個看起來像這樣的XML文檔:Linq to XML使用Take()獲取前兩個元素
<update>
<comments total="4">
<comment>
<person>
<id>SomeID1</id>
<name>SomeName1</name>
<picture>PictureURL1</picture>
</person>
<message>Comment number 1</message>
</comment>
<comment>
<person>
<id>SomeID2</id>
<name>SomeName2</name>
<picture>PictureURL2</picture>
</person>
<message>Comment number 2</message>
</comment>
<comment>
<person>
<id>SomeID3</id>
<name>SomeName3</name>
<picture>PictureURL3</picture>
</person>
<message>Comment number 3</message>
</comment>
<comment>
<person>
<id>SomeID4</id>
<name>SomeName4</name>
<picture>PictureUR4L</picture>
</person>
<message>Comment number 4</message>
</comment>
</comments>
</update>
我想要做的僅僅是前兩個註釋。這是我的代碼:
var commentsList = (from comments in doc.Descendants("comments").Take(2)
select comments.Elements("comment"));
這工作正常,如果文件有兩個或更少的意見,但是當有兩個以上的意見,我得到以下異常:
無法投類型的對象'd__11'鍵入'System.Xml.Linq.XElement
我錯過了什麼嗎?
編輯:我忘了提及,當我嘗試使用foreach循環來通過commentsList循環時引發異常。我嘗試使用.ToList(),但仍然得到相同的異常。
工作正常!謝謝! – HTX9