Are the following two statements the same?
Users user = db.Users.First(u => (u.Username == username));
and
var user = from u in db.Users
where u.Username == username
select u;
Users aUser = user.First();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, both of those queries are identical in function. The compiler will actually take the second query and translate it into the first query as the LINQ language keywords are simply a language extension to C#.
Here is a similar example that shows this to be true:
Using Reflector I was able to see the actual compiled code:
As you can see, the query syntax I typed was changed by the compiler to call the extension methods from the
Enumerableclass. The LINQ query keywords are simply a convenience to the developer that the compiler converts into method calls.Edit: I did notice one difference between your two queries that I didn’t notice at first glance. Your first query will execute slightly faster since it passes a predicate to the
Firstmethod. This will be faster since your second query uses theWheremethod first to filter the results and then grabs the first record. The second query uses two method calls while the first one uses only one.