Reputation: 3298
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
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
Reputation: 10422
Do it in a single statement.
var foo = new[] { 1, 2, 3, 4, 5 }.Select(m=>m/2);
Upvotes: 1
Reputation: 63377
var foo = new int[] { 1,2,3,4,5 };
foo = foo.Select(x=>x/2).ToArray();
Upvotes: 6