views:

4752

answers:

6

If I query a table with a condition on the key field as in:

        var user = from u in dc.Users
                   where u.UserName == usn
                   select u;

I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation.

+8  A: 

Why not something like

var user = dc.Users.SingleOrDefault(u=> u.UserName==usn);
Danimal
FirstOrDefault will do a TOP 1 operation for efficiency. Unfortunately SingleOrDefault does not do a TOP 2 and selects the entire set.
DamienG
A: 

I would use the SingleOrDefault method.

var user = (from u in dc.Users
                   where u.UserName == usn
                   select u).SingleOrDefault();
Joel Cunningham
+19  A: 

Try something like this:

var user = (from u in dc.Users
                   where u.UserName == usn
                   select u).FirstOrDefault();

The FirstOrDefault method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.

smink
Why the downvote?
smink
the downvote doesn't make sense to be -- the code is perfectly cromulent. +1 to bring you back level
Danimal
SO ate my comment, apparently -- his original code, before the edit, would result in an exception.
Adam Lassek
Hum ... i only edited to fix grammar. See revision history.
smink
You're right, the original comment was functional. I could've sworn you used the First() method -- I must be going crazy.
Adam Lassek
+2  A: 

I would use First() or FirstOrDefault().

The difference: on First() there will be an exception thrown if no row can be found.

Sam
+2  A: 

Also it should be noted that First/FirstOrDefault/Single/SingleOrDefault are the point of execution for a LINQ to Sql command. Since the LINQ statement has not been executed before that, it is able to affect the SQL generated (e.g., It can add a TOP 1 to the sql command)

James Curran
A: 

too bad, it does not work this way in SQL 2000. The problem is that link generates the following sql :

select top (1) ...

In sql 2000 is only accepted :

select top 1 ...

So what is the best method ?

allie