ojhawkins
ojhawkins

Reputation: 3298

Using Linq is there a way to perform an operation on every element in an Array

If I have an array

var foo = new int[] { 1,2,3,4,5 };

Using linq can I perform an operation on each element instead of doing something like this?

for (int i = 0; i < foo.Length; i++)
{
    foo[i] = foo[i] / 2; //divide each element by 2
}

Upvotes: 5

Views: 4001

Answers (4)

Nikita B
Nikita B

Reputation: 3333

Those are bad solutions in my opinion. Select().ToArray() creates new collection, meaning that it might cause both performance and memory issues for larger arrays. If you want a shorter syntax - write extension methods:

static class ArrayExtensions
{
    public static void ForEach<T>(this T[] array, Func<T,T> action)
    {
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = action(array[i]);
        }
    }

    public static void ForEach<T>(this T[] array, Action<T> action)
    {
        for (int i = 0; i < array.Length; i++)
        {
            action(array[i]);
        }
    }   
}

//usage
foo.ForEach(x => x/2)
foo.ForEach(x => Console.WriteLine(x));

Upvotes: 4

Atish Kumar Dipongkor
Atish Kumar Dipongkor

Reputation: 10422

Do it in a single statement.

var foo = new[] { 1, 2, 3, 4, 5 }.Select(m=>m/2);

Upvotes: 1

Jin Chen
Jin Chen

Reputation: 642

Use:

foo = foo.Select(p => p / 2).toArray();

Upvotes: 1

King King
King King

Reputation: 63377

var foo = new int[] { 1,2,3,4,5 };
foo = foo.Select(x=>x/2).ToArray();

Upvotes: 6

Related Questions