Alex
Alex

Reputation: 5257

Moving element in array with C#

Is there any way to move items inside an array? For example:

int[] myArray = {1,2,3,4};

2nd element becomes the last:

int[] myArray = {1,3,4,2};

P.S.: No that's not a homework. I can think of at least one solution but it requires rather difficult implementation:

Any other (read - easier) way to do this?

Upvotes: 2

Views: 9253

Answers (5)

anouar.bagari
anouar.bagari

Reputation: 2104

   myArray = new List<int>(myArray.Where((x, i) => (i != 1))) 
               { myArray[1] }.ToArray();

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50245

For this instance, you can use the XOR swap:

[Test]
public void TestSwap()
{
    int[] myArray = { 1, 2, 3, 4 };

    Console.WriteLine(string.Join(", ", myArray));

    Swap(myArray, 1, 2);
    Swap(myArray, 2, 3);

    Console.WriteLine(string.Join(", ", myArray));
}

static void Swap(int[] vals, int x, int y)
{
    vals[x] = vals[x] ^ vals[y];
    vals[y] = vals[y] ^ vals[x];
    vals[x] = vals[x] ^ vals[y];
}

Upvotes: 0

SASS_Shooter
SASS_Shooter

Reputation: 2216

If the array is always a fixed size then:

myArray = new int[4] { myArray[0], myArray[2], myArray[3], myArray[1] };

But if it is variable in size then it becomes trickier and is best done in a List first

int lastElement = 0;
List<int> newArray = new List<int>();
for ( int index=0; index<myArray.Length; index++)
{
     if ( index == 1 ) lastElement = myArray[index];
     else newArray.Add(myArray[index]);
}
newArray.Add(lastElement);
myArray = newArray.ToArray();

Upvotes: 1

itsme86
itsme86

Reputation: 19526

There is no easy way to do it using an array. You'll have to loop through the array shifting every element up to the index that's moving, and then re-insert that element at the end. You could always use a List<int> to do it.

List<int> list = myArray.ToList();
int value = list[1];
list.RemoveAt(1);
list.Add(value);
myArray = list.ToArray();

Upvotes: 8

Matzi
Matzi

Reputation: 13925

Use List<int>. Array is not for such movements of all the elements.

Or try to swap the last and the chosen element, it will mess up the order though.

Upvotes: 3

Related Questions