23

我想知道多个 .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
                )
        );

或者,我可以将它们全部组合到一个 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
                )
        );

Where() 子句链是否会损害性能或它们是否等效?

4

1 回答 1

24

在 LINQ to Objects 中,对性能的影响非常小,因为基本上迭代器链会更长 - 获取下一个元素意味着要向上一长串 MoveNext() 调用。

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

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

于 2011-01-19T13:05:33.560 回答