I want to write something like:
(0 .. 7).ForEach(i => SomeMethod(i))
but either I can't find the correct syntax, or this isn't possible in C#. If it can be done, what is the correct syntax please?
I want to write something like:
(0 .. 7).ForEach(i => SomeMethod(i))
but either I can't find the correct syntax, or this isn't possible in C#. If it can be done, what is the correct syntax please?
 
    
    You can use Enumerable.Range Method
foreach (var i in Enumerable.Range(0, 7)) SomeMethod(i);
And if you add ForEach extension method as @Richard suggested, just do:
Enumerable.Range(0, 7).ForEach(SomeMethod);
 
    
    To achieve what you're after, you'll need to add the illusive and well-known LINQ ForEach statement.
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach(T item in source)
    {
        action(item);
    }
}
Usage:
Enumerable.Range(0, 7).ForEach(i => SomeMethod(i));
Enumerable.Range(0, 7).ForEach(i => Console.WriteLine(i.ToString());
Enumerable.Range(0, 7).ForEach(i => 
{
    string oddEven = i % 2 == 0 ? "even" : "odd";
    Console.WriteLine(string.Format("{0} is {1}", i, oddEven));
}
Extra reading
 
    
    Enumerable.Range(0, 7).ToList().ForEach(i => whatever)
You need ToList, because pure IEnumerable doesn't have ForEach. (Well, you can easily define your own if you need one.)
Or maybe Enumerable.Range(0, 7 + 1), if you want including 7 as well.
