Is it bad practice to use LINQ to iterate and execute actions, and not just to select data?

The big subjective question: I often use LINQ to filter a set of objects, and then, after a query, it executes the old foreach function to perform an action on each of the results. Is there a good way to combine these two tasks in such a way that an action is performed for each object that matches the Where () predicate? Almost like passing an Action to Select (). This is probably not compiled, but what about passing to Func, which returns bool, then you can embed it in another request that can do something with errors or successes. Has anyone done this in production code? Would this be considered bad practice? Any other thoughts?

+5
linq
source share
3 answers

List<T> has a ForEach() method designed for this.

+8
source share

Many people asked for the ForEach method - and it is really convenient (that is why we have one in MoreLINQ ). It is also potentially dangerous.

Most LINQs strongly discourage side effects. They are possible, but discouraged. This is why OrderBy etc. Return new collections, not sort existing ones.

Now consider ForEach - this is an "action", not a function, because it returns nothing. If it has no side effects, this is completely pointless! Thus, this runs counter to part of the LINQ philosophy - it basically does not approach things in a functional style.

I am not trying to make a case for or against, in fact - in practice, I think it is a useful thing, and I am not surprised that this is in many libraries, etc. This is a very obvious pseudo-operator to add. Just think about what you are doing and pay attention to the fact that you are introducing side effects. This is a kind of boundary between the LINQ functional style and the more imperative coding style.

+11
source share

In IEnumerable, you can implement the ForEach extension method .

+2
source share

All Articles