Using Linq is a way to perform an operation on each element of an array.

If i have an array

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

Using linq , can I do 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 } 
+4
source share
4 answers
 var foo = new int[] { 1,2,3,4,5 }; foo = foo.Select(x=>x/2).ToArray(); 
+6
source

These are bad decisions, in my opinion. Select().ToArray() creates a new collection, which means that it can cause performance and memory problems for large arrays. If you want to use 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)); 
+2
source

Do it in one expression.

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

Using:

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

Source: https://habr.com/ru/post/1498126/


All Articles