在
Linq to对象中,此代码之间的执行有任何不同:
var changedFileIDs = updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID);
var changedVaultFiles = filesToUpdate.Where(x => changedFileIDs.Contains(x.ID));
foreach (var file in changedVaultFiles)
{
Vault.Upload(file);
}
和这段代码?
var changedVaultFiles = filesToUpdate.Where(x => updatedFiles.Where(file => file.CurrentVersion != file.OriginalVersion).Select(file => file.ID).Contains(x.ID));
foreach (var file in changedVaultFiles)
{
Vault.Upload(file);
}
最佳答案 不,性能没有区别,因为Linq的一个特性是
deferred execution,换句话说,在查询变量在foreach或for或者调用ToList或ToArray扩展中迭代之前,查询不会被执行方法.因此,在您的第一个示例中,您正在编写主要查询,但在迭代之前不会执行.
您将在此link中找到有关查询执行如何在LINQ中工作的更多详细信息.
延期执行摘要:
After a LINQ query is created by a user, it is converted to an command
tree. A command tree is a representation of a query.The command tree
is then executed against the data source when the query variable is
iterated over, not when the query variable is created. At query
execution time, all query expressions (that is, all components of the
query) are evaluated, including those expressions that are used in
result materialization.