var q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points").**Value.ToString()**;
I would like to get q as a type string aft开发者_如何学编程er executing this query. Even after keeping the extra bolded line this is giving me some IEnumerable type.
Well let me put it this way. I would like to make the above query something like below one without the runtime throwing any error.
string q = from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points");
Any help?
var q = (from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points")).FirstOrDefault();
Enumerable.FirstOrDefault Method (IEnumerable)
LINQ will always return an enumerable result. To get it to evaluate and return one result you can use
.First()
.FirstOrDefault()
.Single()
.SingleOrDefault()
depending on your requirement.
The query will return IEnumerable even if the result contains single record. Try this -
if q.count() > 0
var singleQ = q.First();
Or if you are sure that there will be atleast one record then do it like this -
string q = (from child in doc.Descendants("level")
where (int)child.Attribute("id") == 55
select (string)child.Element("Points")).First();
精彩评论