C# – Existing LINQ extension method similar to Parallel.For?

c++extension-methodsiterationlinq

Possible Duplicate:
LINQ equivalent of foreach for IEnumerable<T>

The linq extension methods for ienumerable are very handy … but not that useful if all you want to do is apply some computation to each item in the enumeration without returning anything. So I was wondering if perhaps I was just missing the right method, or if it truly doesn't exist as I'd rather use a built-in version if it's available … but I haven't found one 🙂

I could have sworn there was a .ForEach method somewhere, but I have yet to find it. In the meantime, I did write my own version in case it's useful for anyone else:

using System.Collections;
using System.Collections.Generic;

public delegate void Function<T>(T item);
public delegate void Function(object item);

public static class EnumerableExtensions
{
    public static void For(this IEnumerable enumerable, Function func)
    {
        foreach (object item in enumerable)
        {
            func(item);
        }
    }

    public static void For<T>(this IEnumerable<T> enumerable, Function<T> func)
    {
        foreach (T item in enumerable)
        {
            func(item);
        }
    }
}

usage is:

myEnumerable.For<MyClass>(delegate(MyClass item) { item.Count++; });

Best Solution

Shedding a little more light on why:

LINQ is functional in nature. It is used to query data and return results. A LINQ query shouldn't be altering the state of the application (with some exceptions like caching). Because foreach doesn't return any results, it doesn't have many uses that don't involve altering the state of something besides what you are passing in to it. And if you need a Foreach() extension method, it is easy to roll your own.

If, on the other hand, what you want is to take input and call a function on each item that returns a result, LINQ provides a way through its select method.

For example, the following code calls a function delegate on every item in a list, returning true if that item is positive:

    static void Main(string[] args)
    {
        IEnumerable<int> list = new List<int>() { -5, 3, -2, 1, 2, -7 };
        IEnumerable<bool> isPositiveList = list.Select<int, bool>(i => i > 0);

        foreach (bool isPositive in isPositiveList)
        {
            Console.WriteLine(isPositive);
        }

        Console.ReadKey();        
    }