Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

You can use this method:

public static class Extension
{
    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (var t in source)
        {
            action(t);
        }
        return source;
    }
}

It returns the source so you can pass it along to another extension method as needed. Or if you want to be void, you can change the method a little bit.

The morelinq project has a ForEach operator. LINQ itself doesn't, as LINQ is all about functional programming, and ForEach has side effects.

Here is a similar dicussion on this Run a method on all objects within a collection

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top