将 foreach 更改为 lambda
我需要帮助来简化这个陈述。如何将 foreach 更改为 lambda
var r = mp.Call(c => c.GetDataset()); // returns IEnumerable of dataset
foreach (DatasetUserAppsUsage item in r)
{
datasetUserAppsUsage.Merge(item.AppsUsageSummary);
}
I need a help with simpify this statement. How to change foreach to lambda
var r = mp.Call(c => c.GetDataset()); // returns IEnumerable of dataset
foreach (DatasetUserAppsUsage item in r)
{
datasetUserAppsUsage.Merge(item.AppsUsageSummary);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
lambda 和循环是正交的。试图将它们强行改变为另一种是不合适的。那个代码没问题。留下它。
您可以获得
.ForEach
实现,但它不会使代码变得更好(事实上,它会更难遵循,即更糟),并且它赢了效率不会更高(事实上,它会稍微慢一些,即更糟)。lambdas and loops are orthogonal. It is inappropriate to try to change them to brute-force one into the other. That code is fine. Leave it.
You can get
.ForEach
implementations, but it isn't going to make the code better (in fact, it will be harder to follow, i.e. worse), and it won't be more efficient (in fact, it will be marginally slower, i.e. worse).您可以执行以下操作
You can do the following
就我个人而言,我不认为我会将其合并到单个 lambda 中。你可以这样做:
但是,我会避免它,因为它是 故意造成副作用,这确实违背了LINQ的预期,而且其意图也不是很明确。
Personally, I don't think I would merge this into a single lambda. You could do:
However, I would avoid it, as it's purposefully causing side effects, which really violates the expectations of LINQ, and is not very clear in its intent.
我同意 lambda 的目的不同,但有时我会使用这个技巧:
技巧是使用 All() 并返回 true 以避免中断。
当然,在枚举器内部时不要更改底层集合:)
I agree that lambdas purpose it different, but sometimes I use this trick:
The trick is to use All() and return true to avoid break.
And do not change the underlying collection when inside enumerator of course :)