【问题标题】:XDocument.Descendants("somethinghere").Count() method does not existXDocument.Descendants("somethinghere").Count() 方法不存在
【发布时间】:2011-06-04 19:35:36
【问题描述】:

我正在尝试使用LINQ to XML 对一些后代进行简单计数,但我不存在“Count()”方法吗?

例子:

using System.Xml.Linq;

XDocument doc = XDocument.Load( "somexmlfile" );
int count = doc.Descendants("somethinghere").Count();

上面的代码无法编译,因为它无法识别Count() 方法。

【问题讨论】:

  • 文件顶部有using System.Linq;吗?
  • 不,这解决了它!你的男人!

标签: c# xml linq


【解决方案1】:

文件顶部有using System.Linq;吗?

【讨论】:

    【解决方案2】:

    这是因为Descendants(XName name) 返回一个IEnumerable<XElement>。

    根据设计,IEnumerable 延迟加载数据,因此对集合中的项目进行计数会导致发生枚举。

    我可能会将其转换为具有 Count 属性的 IList,您可以使用它。

    【讨论】:

    • 我知道这一切,只是我在网上找到了许多显示 XDocument.Descendants().Count() 的示例,并且很困惑为什么我没有那个方法。现在我知道为什么要感谢 svick。
    • 如果您只想计算元素数量,那么转换为列表就大材小用了。
    • 他很可能会做其他事情,而不仅仅是计算它们,在这种情况下,对集合进行两次迭代将是多余的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    相关资源
    最近更新 更多