XDocument.Descendants ("somethinghere"). Count () method does not exist

Am I trying to do a simple count of some descendants using LINQ to XML and does the Count () method not exist for me?

Example:

using System.Xml.Linq; XDocument doc = XDocument.Load( "somexmlfile" ); int count = doc.Descendants("somethinghere").Count(); 

The above will not compile because it does not recognize the Count() method.

+4
source share
2 answers

You have using System.Linq; at the top of the file?

+7
source

This is because Descendants(XName name) returns an IEnumerable<XElement> .

By design, IEnumerable lazy loads data, and so counting items in a collection will result in an enumeration.

I would probably convert it to an IList that has a Count property that you can use.

+3
source

All Articles