My question is how to do math operations to all the values in an array. I've been doing the whole for looping for each value, but it just made me wonder if there was some easier way to type it out, and/or something that increases performance.
For example:
int[] numbers;
numbers[0] = 0;
numbers[1] = 1;
Now, I'm not entirely concerned with taking [0] and [1], and adding or subtracting them. More like, how do I add 3 to all of them, without using a loop?
You can use LINQ to apply a function to all values in an Enumerable (for example array or List).
var result = numbers.Select(i => i + 3);
This is the full code snippet:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var numbers = new int[2] {0,1};
var result = numbers.Select(i => i + 3);
result.ToList().ForEach(Console.WriteLine);
}
}
static void Main(string[] args)
{
var numbers = new[] { 1, 2, 3 };
numbers = numbers.Select(i => i +3).ToArray();
foreach(var numb in numbers)
{
Console.WriteLine(numb);
}
Console.ReadKey();
}
Here it will add 3 to every element of the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With