Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing Arthimetic to all values in an Array

Tags:

arrays

c#

math

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?

like image 572
Alexander Meyers Avatar asked Jan 31 '26 10:01

Alexander Meyers


2 Answers

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); 
    }
}
like image 175
Alex Avatar answered Feb 03 '26 00:02

Alex


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.

like image 27
mybirthname Avatar answered Feb 03 '26 01:02

mybirthname