LINQ的所有Foreach源VS [英] Linq All Vs Foreach

查看:104
本文介绍了LINQ的所有Foreach源VS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想了解所有和foreach Linq中之间的差异。

Hi I am trying to understand differences between All and ForEach in Linq.

我知道,所有用于检查的条件,并返回布尔如果谓词是满意。但是,当我有它只是工作正常谓词内部的分配和DONOT抱怨。

I know that All is used for checking a condition and returns bool if the predicate is satisfied. But when i have an assignment inside the predicate it simply works fine and donot complain.

什么是在这种情况下使用的foreach?或者是什么的情况下使得它使用的foreach

What is the use of ForEach in that case? Or what cases makes it use of ForEach

这可能是有点傻,但需要知道的意义

It might be little silly but need to know significance

推荐答案

有在LINQ(故意)实际上没有的ForEach 是。有一个列表< T> .ForEach 方法,它运行列表中的每个对象的动作

There is actually no ForEach in LINQ (on purpose). There is a List<T>.ForEach method, which runs an action on each object in the list.

主要的区别是所有是一个过滤器 - 如果所有项目比赛的谓词返回true。 列表< T> .ForEach 的存在是为了创造的副作用 - 你运行列表中的每个项目的一些操作。

The main difference is All is a filter - it returns true if all of the items match a predicate. List<T>.ForEach exists to create side effects - you run some operation on each item within the list.

在一般情况下,我会避免与LINQ引起副作用的查询(即:不做查询操作),而是把它们放在一个的foreach 循环之后。这使得意图非常明确,这有助于维护。

In general, I'd avoid queries with LINQ that cause side effects (ie: don't do the operation in the query), and instead put them in a foreach loop afterwards. This makes the intention very clear, which helps maintainability.

注意列表< T> .ForEach 实际上从WinRT的框架中删除,因为它确实不增添了不少价值。埃里克利珀写了主题一个大文章使用的foreach 而不是列表< T> .ForEach

Note that List<T>.ForEach was actually removed from the WinRT framework, since it really doesn't add a lot of value. Eric Lippert wrote a great article on the subject of using foreach instead of List<T>.ForEach.

这篇关于LINQ的所有Foreach源VS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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