Best way for retrieving single record results in LINQ to SQL

Viewed 78134

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.

6 Answers

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.

Why not something like

var user = dc.Users.SingleOrDefault(u=> u.UserName==usn);

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)

I would use First() or FirstOrDefault().

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

I would use the SingleOrDefault method.

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