简体   繁体   English

L2E这两个是同一回事吗?

[英]L2E these two are the same thing?

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();

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#. 编译器实际上将执行第二个查询并将其转换为第一个查询,因为LINQ语言关键字只是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: 使用Reflector,我可以看到实际的编译代码:

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. 如您所见,编译器更改了我键入的查询语法,以从Enumerable类调用扩展方法。 The LINQ query keywords are simply a convenience to the developer that the compiler converts into method calls. LINQ查询关键字只是开发人员的方便,编译器将其转换为方法调用。

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. 由于将谓词传递给First方法,因此第一个查询的执行速度会稍快。 This will be faster since your second query uses the Where method first to filter the results and then grabs the first record. 由于您的第二个查询首先使用Where方法来过滤结果,然后获取第一条记录,因此这将更快。 The second query uses two method calls while the first one uses only one. 第二个查询使用两个方法调用,而第一个只使用一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM