Search code examples
c#linqoperation

C# Linq question


Does LINQ have a sequence operator, which allows to perform some action on every element without projecting it to a new sequence?

This might see a bit awkward, but just for me to know :)

Example:

IEnumerable<IDisposable> x;
x.PERFORM_ACTION_ON_EVERY_ELEMENT(m => m.Dispose());

Obviously, this could be done using something like:

foreach (var element in x) x.Dispose();

But if something actually exists, that would be nice.


Solution

  • No, it doesn't exist. Specifically for the reason you mention: It seems awkward having a single operator that behaves completely different than all the others.

    Eric Lippert, one of the C# Compiler developers has an article about this.

    But we can go a bit deeper here. I am philosophically opposed to providing such a method, for two reasons.

    The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.

    The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a “statement expression” context.)

    It does not sit well with me to make the one and only sequence operator that is only useful for its side effects.