gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:22:54 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com