Home > Software engineering >  Access last 3 elements of the array in c# and perform action in a single statement
Access last 3 elements of the array in c# and perform action in a single statement

Time:07-19

For example, I have n number of integer array elements in c#. Can we access the last 3 elements of the array and modify these elements for instance multiple each element by 4. Can we achieve this in a single statement instead of using foreach/for loop(can we use the regular expression)?

Before operation

arr[0] = 3

.. ..

arr[n-3] = 1

arr[n-2] = 5

arr[n-1] = 6

After operation

arr[0] = 3

.. ..

arr[n-3] = 4

arr[n-2] = 20

arr[n-1] = 24

CodePudding user response:

You can do this:

var arr = new int[] {1, 2, 3, 4, 5};
        
var result = arr.TakeLast(3).Select(x => x * 4).ToArray();

p.s. this is done in .NET 6

CodePudding user response:

With C# 8 (i.e. dotnet core 3) and later you can also use Ranges to write as a one-liner:

int[] a = { 3, 4, 5, 6, 7, 8, 9, 1, 5, 6 };

var result = a[..^3].Concat(a[^3..].Select(e => e * 4));

a[..^3] does return all elements except the last 3.

a[^3..] does return the last 3 elements, which are then multiplied by 4.

The two arrays are then concatenated.

If you want to use result as an array, add ToArray().

CodePudding user response:

If you do not have a formula that applies to all of them you could use tuples:

int []x = new[] {10, 20, 30, 40, 50, 60};

var len =x.Length;

(x[len-3], x[len-2], x[len-1]) = (6, 7659, 854);

Of course, this only works if the array has at least 3 elements. If you have a formula and need to select a dynamic number of items for update, then @Jim de Vries' answer works best.

CodePudding user response:

You can use arr.Length and sub by 3, 2, 1 Like:

int[] arr = new int[] { 1, 2, 3, 4, 5, 6 };
int arrLength = arr.Length;
Console.WriteLine("Before Operation: {0}", string.Join(", ", arr));

arr[arrLength - 3] *= 4;
arr[arrLength - 2] *= 4;
arr[arrLength - 1] *= 4;
Console.WriteLine("After operation: {0}", string.Join(", ", arr));

CodePudding user response:

You can use LINQ for same. Below is the sample code.

int[] arr = new[] { 1, 3, 3, 3, 5 };
int elementsCount = 3;
int multiplier = 4;
var result = arr.Take(arr.Length - elementsCount).Concat(arr.Skip(arr.Length - elementsCount).Select(a => a * multiplier)).ToArray();
  • Related