Search code examples
c#.netlinqenumerable

Equivalence of Observable.Do for Enumerable


Theres a Do method in System.Reactive to a execute a mutator for each item in the sequence.

Is there any equivalent method for IEnumerable either in standard library or third parties like morelinq?


Solution

  • LINQ query operators are generally meant to be free from side-effects. You could just use a foreach loop to "do" your thing.

    Or do it in a Select or Where method if you don't care about side effects:

    enumerable.Select(x => { /*do something here */ return x; })
    

    For a List<T>, there is a ForEach extension method that can be used to execute an Action<T> for each element.