Reputation: 1357
I am attempting to query an XML document and return a count stored in a COUNT tag inside of a METEDATA tag. The thing is that I am having difficulty in accessing the property strCount for use in the program. Ive considered looping through the IEnumerable but was hoping to be able to access he value in a cleaner manner. Such as return countQ.strCount our countQ["strCount"]. I knw those do not work in this instance but wanted to illustrate the desire to use the name of the property I want the value as opposed to indexing or a loop.
CODE
Private XDocument doc = XDocument.Load(path);
public class entityCount
{
public string strCount { get; set; }
}
public IEnumerable<entityCount> queryCount(){
var countQ = this.doc.Descendants("METADATA") .Select(m => new entityCount {
strCount = m.Element("COUNT").Value
});
return countQ.....?;
}
ABBREVIATED XML
<PRODUCTION_SET>
<METADATA>
<COUNT>322</COUNT>
</METADATA>
<ENTITY>
<METADATA>
<ID>1</ID>
<foo>x</foo>
<bar>y</bar>
</METADATA>
</ENTITY>
.
.
.
.
.
<ENTITY>
<METADATA>
<ID>322</ID>
<foo>x</foo>
<bar>y</bar>
</METADATA>
</ENTITY>
</PRODUCTION_SET>
Upvotes: 2
Views: 318
Reputation: 503
To get the count in the first metadata tag, you could just do this: countQ.First()
If what you're interested is only the metadata tag directly in PRODUCTION_SET, you should probably not use Descendants (which would go looking for it deeper, even in individual entities, ignoring the context), but instead find the PRODUCTION_SET tag and then do .Elements().Select(...).Single()
. Single() is almost the same as First(), but it will make sure there is only one element you're looking for. In that case, the code would look like this:
public entityCount queryCount(){
return this.doc.Root.Elements("METADATA").Select(m => new entityCount {
strCount = m.Element("COUNT").Value
}).Single();
}
Upvotes: 3
Reputation: 62498
you can get the first item of the IEnumerable<T>
using First()
or FirstOrDefault()
like:
var queryCountResult = countQ.FirstOrDefault();
if(queryCountResult !=null)
{
var count = queryCountResult.strCount;
}
Upvotes: 0
Reputation: 35318
You can convert the the IEnumerable<T> to a list and access the elements via their indices:
int cnt = countQ.ToList()[0].strCount;
return cnt;
The question is, does your query only ever return one item? If you know that you only have one item, you can just use First()
:
int cnt = countQ.First().strCount;
return cnt;
Upvotes: 2