views:

23

answers:

1

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();
+3  A: 

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 System;
using System.Linq;

class Example
{
    static void Main()
    {
        var names = new[] { "Andrew", "Nicole", "Michael",
            "Joe", "Sammy", "Joshua" };

        var shortNames = from n in names
               where n.Length == 6
               select n;
        var first = names.First();
    }
}

Using Reflector I was able to see the actual compiled code:

internal class Example
{
    private static void Main()
    {
        string[] names = new string[] { "Andrew", "Nicole", "Michael", "Joe", "Sammy", "Joshua" };
        IEnumerable<string> shortNames = names.Where<string>(delegate (string n) {
            return n.Length == 6;
        });
        string first = names.First<string>();
    }
}

As you can see, the query syntax I typed was changed by the compiler to call the extension methods from the Enumerable class. 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 First method. This will be faster since your second query uses the Where method 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.

Andrew Hare