I have a byte array, for example:
{0,1,2,3,4,5,6,7,8,9}
I want to insert the smaller array into:
The array which I want to insert after the third index of the original array:
{11,11,11}
So the final array should look like this:
{0,1,2,3,11,11,11,4,5,6,7,8,9}
as you can see I need to keep the original values of the array, shift them left, and put the new array instead of it. I was looking into Array.Copy() But it's overwriting the original values, not shifting them
CodePudding user response:
You can try using Linq to query array
and assign the result back to it:
using System.Linq;
...
int[] array = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] insert = new int[] {11, 11, 11};
array = array
.Take(4)
.Concat(insert)
.Concat(array.Skip(4))
.ToArray();
If you are looking for low level Array
methods:
int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] insert = new int[] { 11, 11, 11 };
int at = 4;
Array.Resize<int>(ref array, array.Length insert.Length);
Array.Copy(array, at, array, at insert.Length, array.Length - at - insert.Length);
Array.Copy(insert, 0, array, at, insert.Length);
CodePudding user response:
You can convert your array to an list. A list is like an array, but you can easily add, insert or remove values. See this code:
int[] array = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] insert = new int[] {11, 11, 11};
List<int> list = new List<int>(array);
list.InsertRange(4, insert);
array = list.ToArray(); // convert the list back to an array
Online demo: https://dotnetfiddle.net/GeEAeU