views:

63

answers:

3
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 after 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?

A: 

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();
Ramesh Soni
Thanks Ramesh..
async
Your first one - testing `(q.count() > 0)` first - will evaluate the query twice won't it? Once to check the count then once to read the value. If you use `First` or `FirstOrDefault` then it should only evaluate it once.
Rup
you can use `Any()` instead.
CD
+4  A: 
var q = (from child in doc.Descendants("level")
        where (int)child.Attribute("id") == 55
        select (string)child.Element("Points")).FirstOrDefault();

Enumerable.FirstOrDefault Method (IEnumerable)

CD
That's kewl..thanks CD..I'm falling in love with this LINQ stuffs.
async
+2  A: 

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.

Jamiec