Linq All Vs Foreach

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

I know that All is used to check the condition and returns bool if the predicate is executed. But when I have a task inside the predicate, it just works fine and donot complains.

What is the use of ForEach in this case? Or in what cases it uses ForEach

It may be a little silly, but you need to know the meaning

+7
c # linq
source share
1 answer

LINQ does not actually have ForEach (specifically). There is a List<T>.ForEach that triggers an action for each object in the list.

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

In general, I would avoid queries with LINQ that cause side effects (i.e. do not perform an operation in the query) and instead put them in a ForEach loop. This makes the goal very clear, which helps maintainability.

Note that List<T>.ForEach has actually been removed from WinRT, as it does not really add much value. Eric Lippert wrote a great List<T>.ForEach article using ForEach instead of List<T>.ForEach .

+13
source share

All Articles