c# - Linq to objects 多语句与单语句

标签 c# .net linq

在 Linq to objects 中,这段代码的执行有什么区别吗:

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 ,换句话说,直到查询变量在 foreachfor 中迭代,或调用 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.

关于c# - Linq to objects 多语句与单语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997270/

相关文章:

c# - MongoDB InsertMany与BulkWrite

c# - 从 List<byte> 中删除空字节

.net - 使用 mono 提高 .Net XML 序列化程序的性能

.net - 字符串格式日期 - C# 或 VB.NET

c# - Linq GroupBy - 如何在运行时指定分组键?

c# - Linq 连接两个值

c# - 如何在 ASP.NET 和 C# 中的每个 session 中将 "temporarily"图像存储在 Web 服务器上

c# - 'await' 运算符只能在 async > 方法中使用

c# - .NET 中是否可以对 Threadpool 中的任务进行优先级排序?

c# - 用于构造 OData 查询选项的强类型 Linq