将 foreach 更改为 lambda

发布于 2024-10-22 19:13:28 字数 250 浏览 3 评论 0原文

我需要帮助来简化这个陈述。如何将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鹿童谣 2024-10-29 19:13:28

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).

地狱即天堂 2024-10-29 19:13:28

您可以执行以下操作

r.ToList().ForEach(item => datasetUserAppsUsage.Merge(item.AppsUsageSummary);

You can do the following

r.ToList().ForEach(item => datasetUserAppsUsage.Merge(item.AppsUsageSummary);
征﹌骨岁月お 2024-10-29 19:13:28

就我个人而言,我不认为我会将其合并到单个 lambda 中。你可以这样做:

mp.Call(c => c.GetDataset()).ToList().ForEach(item =>  datasetUserAppsUsage.Merge(item.AppsUsageSummary)); 

但是,我会避免它,因为它是 故意造成副作用,这确实违背了LINQ的预期,而且其意图也不是很明确。

Personally, I don't think I would merge this into a single lambda. You could do:

mp.Call(c => c.GetDataset()).ToList().ForEach(item =>  datasetUserAppsUsage.Merge(item.AppsUsageSummary)); 

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.

心房敞 2024-10-29 19:13:28

我同意 lambda 的目的不同,但有时我会使用这个技巧:

mp.Call(c => c.GetDataset())
  .All(a => { datasetUserAppsUsage.Merge(a.AppsUsageSummary); return true; });

技巧是使用 All() 并返回 true 以避免中断。
当然,在枚举器内部时不要更改底层集合:)

I agree that lambdas purpose it different, but sometimes I use this trick:

mp.Call(c => c.GetDataset())
  .All(a => { datasetUserAppsUsage.Merge(a.AppsUsageSummary); return true; });

The trick is to use All() and return true to avoid break.
And do not change the underlying collection when inside enumerator of course :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文