简体   繁体   English

Linq来对象多个语句与单个语句

[英]Linq to objects multiple statements vs. single statement

In Linq to objects is there any difference in the execution between this code: 在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);
}

and this code? 和这段代码?

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

No, there is no difference in performance, because one of the features of Linq is deferred execution , in other words, your query is not going to be executed until the query variable is iterated over in a foreach or for , or calling ToList or ToArray extension method. 不,在性能上没有什么区别,因为LINQ的的特点之一就是延迟执行 ,换句话说,您的查询是不会被执行,直到查询变量是在迭代结束foreachfor ,或调用ToListToArray扩展方法。 So in your first example your are composing your main query but is not going to be executed until you iterate over it. 因此,在您的第一个示例中,您正在编写主要查询,但在迭代之前不会执行。

You will find in this link more details about how query execution works in LINQ. 您将在此链接中找到有关查询执行如何在LINQ中工作的更多详细信息。

Summary of Deferred Execution : 延期执行摘要:

After a LINQ query is created by a user, it is converted to an command tree. 在用户创建LINQ查询后,它将转换为命令树。 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. 在查询执行时,将评估所有查询表达式(即查询的所有组件),包括在结果实现中使用的那些表达式。

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

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