我什么时候在原生的foreach循环中使用List< T> .ForEach? [英] When would I use List<T>.ForEach over a native foreach loop?

查看:184
本文介绍了我什么时候在原生的foreach循环中使用List< T> .ForEach?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法都有优势吗?如果我需要遍历List项目并对每个项目执行一个操作,我应该使用传统的foreach循环机制还是移动到List.ForEach?

Are there advantages to either approach? If I need to traverse List items and perform an action on each one, should I use the traditional foreach loop mechanism or move on to List.ForEach?

Matthew Podwysocki @ CodeBetter.com撰写了一篇关于反对广告系列。这让我想到一个循环试图解决的问题。在这篇文章中,Matthew认为,显式的循环结构让你思考如何而不是什么。

Matthew Podwysocki @ CodeBetter.com wrote an interesting article about the anti-for campaign. This got me thinking about the problem a loop is trying to solve. In this article, Matthew argues that explicit loop structures make you think about the 'how' instead of the 'what'.

使用其中一个的好理由是什么(如果有的话)?

What are some good reasons to use one over the other (if there are any)?

推荐答案

有一件事,如果你通过代理来申请任何原因,你会使用它。例如,您可以创建自己的列表,填充它等,然后对每个条目应用一个委托。此时,写入:

For one thing, you'd use it if you'd been passed the delegate to apply for whatever reason. For example, you might create your own list, populate it etc and then apply a delegate to each entry. At that point, writing:

list.ForEach(action);

foreach (Item item in list)
{
    action(item);
}

这篇关于我什么时候在原生的foreach循环中使用List< T> .ForEach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆