array map in csharp

In C#, you can use the Array.ConvertAll method to map the elements of an array to a new set of values. Here's an example using a lambda expression to multiply each element of an array by 2:

main.cs
int[] numbers = { 1, 2, 3, 4, 5 };
int[] result = Array.ConvertAll(numbers, x => x * 2);
// result will now be { 2, 4, 6, 8, 10 }
130 chars
4 lines

Alternatively, you can use LINQ's Select method to achieve the same effect:

main.cs
int[] numbers = { 1, 2, 3, 4, 5 };
int[] result = numbers.Select(x => x * 2).ToArray();
// result will now be { 2, 4, 6, 8, 10 }
129 chars
4 lines

Both of these methods create a new array and do not modify the original array.

gistlibby LogSnag