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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With