Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq All Vs Foreach

Tags:

c#

.net

linq

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

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.

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

like image 845
WPFKK Avatar asked Sep 25 '13 16:09

WPFKK


1 Answers

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.

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.

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.

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.

like image 66
Reed Copsey Avatar answered Sep 24 '22 02:09

Reed Copsey