views:

118

answers:

3

For example

int[] Array = { 1, 23, 4, 5, 3, 3, 232, 32, };

Array.JustDo(x => Console.WriteLine(x));
+6  A: 

You can use the Array.ForEach method

int[] array = { 1, 2, 3, 4, 5};
Array.ForEach(array, x => Console.WriteLine(x));

or make your own extension method

void Main()
{
    int[] array = { 1, 2, 3, 4, 5};
    array.JustDo(x => Console.WriteLine(x));
}

public static class MyExtension
{
    public static void JustDo<T>(this IEnumerable<T> ext, Action<T> a)
    {
        foreach(T item in ext)
        {
            a(item);
        }
    }
}
John Buchanan
int[] array hasn't that extension method but It is nice to know collection has this extension.
Freshblood
Writing extension method is also not bad.
Freshblood
+12  A: 

I think you're looking for Array.ForEach which doesn't require you to convert to a List<> first.

int[] a = { 1, 23, 4, 5, 3, 3, 232, 32, };
Array.ForEach(a, x => Console.WriteLine(x));
Brian R. Bondy
int[] array hasn't that extension method.
Freshblood
@Freshblood - but the array class does. You just have to do it like the sample shows.
Joel Coehoorn
@Freshblood: If you look at my code example Array is not the name of the int array it's the name of the Array class. And yes it works with int arrays as my code demonstrates. You can compile it and try it.
Brian R. Bondy
@Brian sorry.At a glance i haven't seen that you defined int[] a but i had defined int[] array :) thats why i haven't consider your extension method
Freshblood
@Freshblood: np, I had to change the name of the variable for that reason :)
Brian R. Bondy
It was funny coincidence :)
Freshblood
Also, be careful with this. It works because `Console.Writeline()` has an overload that accepts `int` (and `object`, for that matter). If you're expecting a `string` there you'll be surprised.
Joel Coehoorn
Yep, i am aware of it.
Freshblood
+2  A: 

As others have said, you can use Array.ForEach. However, you might like to read Eric Lippert's thoughts on this.

If you still want it after reading that, there is the Do method in the System.Interactive assembly which is part of Reactive Extensions, as part of EnumerableEx. You'd use it like this:

int[] array = { 1, 23, 4, 5, 3, 3, 232, 32, };   
array.Do(x => Console.WriteLine(x));

(I've changed the name of the variable to avoid confusion. It's generally better not to name variables with the same name as a type.)

There's plenty of great stuff to look at in Reactive Extensions...

Jon Skeet
I can't find System.Interactive namespace ....
Freshblood
@Freshblood: No, it's in the System.Interactive assembly which is part of Reactive Extensions. I think it's still in the System.Linq namespace. I'll edit my post to make this clearer.
Jon Skeet