c# - Linq to XML 使用 Take() 获取前两个元素

标签 c# linq-to-xml

我正在努力思考 Linq to XML。我有一个如下所示的 XML 文档:

<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"));

如果文档有两个或更少的评论,这工作正常,但当有两个以上的评论时,我得到以下异常:

Unable to cast object of type 'd__11' to type 'System.Xml.Linq.XElement

我错过了什么吗?

编辑:我忘了提到当我尝试使用 foreach 循环遍历 commentsList 时抛出异常。我也尝试使用 .ToList() 但仍然遇到相同的异常。

最佳答案

可以直接跳转到评论元素。

var commentsList = doc.Descendants("comment").Take(2);

关于c# - Linq to XML 使用 Take() 获取前两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12207156/

相关文章:

c# - 从 XML 文件填充 ListView

.net - 使用 XDocument 时如何在属性值中保留空格?

C# WPF D3(动态数据显示)图表项目

c# - 编译时向量数学维度一致性检查

c# - C# 中对 GRPC 的 TLS 支持

c# - Linq To Xml - 从重复的 XML 创建字典

c# - 如何使用 LINQ 选择内部 XML 节点的集合?

c# - 如何只搜索 XDocument 的子项,而不是其所有后代?

c# - 组合框不在 C# 的 DataGridView 中显示默认值

c# - session 值在回发和页面刷新时变为空