LINQ中的多个.Where()语句是性能问题吗?

Joh*_*ohn 20 c# linq performance clause where

我想知道多个.Where()语句是否存在性能影响.例如我可以写:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
        )
    .Where(
        c1 =>
            !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
        )
    .Where(
        c1 =>
            !Context.EmployeeTask.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );
Run Code Online (Sandbox Code Playgroud)

或者我可以将它们全部组合到一个Where()子句中,如下所示:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
            && !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
            && !Context.Employee_Task.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );
Run Code Online (Sandbox Code Playgroud)

Where()子句链是否会影响性能或它们是否相同?

Jon*_*eet 19

在LINQ to Objects中,将会有非常小的性能损失,因为迭代器链基本上会更长 - 获取下一个元素意味着需要进行长链的MoveNext()调用.

在LINQ to SQL和类似的提供程序中,我希望以任何一种方式生成相同的SQL,因此它不会影响那里的性能.

编辑:自写这篇文章以来,我发现了更多关于LINQ to Objects实现的内容 - 它有点复杂 ......

  • @ekkis:是的; 如果你把一个廉价的过滤器放在首先摆脱大多数候选元素,那将会加快速度. (3认同)