views:

101

answers:

1

this query will just one row as a result

    myDataContext db = new myDataContext();
    var query = from u in db.users
                where u.userId == myUserId
                select u;

I usually get the result out from the "query" object by using "foreach"

    foreach(var i in query){
        username =  i.username;
    } 
    Response.Write(username);

but that does not make sense if case if the object have just one row
so what is the best way to fetch data from object when I am sure it just have one row?

+2  A: 

just use query.Single().

Dave Markle
thanks, I knew it should be simple :)
ahmed
what about SingleOrDefault() - I still don't really get where the default comes from.
MrChrister
Single() will throw an exception if there is no record, or more than one record. SingleOrDefault() will return NULL if no record exists. SingleOrDefault() will throw if multiple records exist. If you don't want an exception for multiple records, use First() or FirstOrDefault().
Dave Markle