-2

I have a array which contains 7 elements and i need to move 5 and 6 index elements to 1 and 2 position and vice versa

say for example

 ItemParameter[] parameters = {a,b,c,d,f,g,h};

and i need

 {a,g,h,d,f,b,c}
usefulBee
  • 9,250
  • 10
  • 51
  • 89
user3301440
  • 800
  • 6
  • 13
  • 27
  • This is oddly specific. Is this a specific example of a more general case that you want to solve? Also the lack of `e` in the example is making me twitch slightly. ;) As is the duplicated `a` in the expected output... – Matthew Watson Jun 18 '15 at 13:38
  • Your example doesn't match your description. You go from a 7-element array to an 8-element array? – sstan Jun 18 '15 at 13:39
  • possible duplicate of [Swap two items in List](http://stackoverflow.com/questions/2094239/swap-two-items-in-listt) – sstan Jun 18 '15 at 13:48

4 Answers4

11

Using an extension method defined as:

public static void Switch<T>(this IList<T> array, int index1, int index2)
{
    var aux = array[index1];
    array[index1] = array[index2];
    array[index2] = aux;
}

use simply as:

ItemParameter[] arr = {a,b,c,d,f,g,h};
arr.Switch(2, 6);
arr.Switch(1, 5);
Andrei Tătar
  • 7,872
  • 19
  • 37
2
ItemParameter[] arr = {a,b,c,d,f,g,h};

// swap elements of index 1 and 5
var tmp = arr[1];
arr[1] = arr[5];
arr[5] = tmp;

// swap elements of index 2 and 6
tmp = arr[2];
arr[2] = arr[6];
arr[6] = tmp;
SimpleVar
  • 14,044
  • 4
  • 38
  • 60
1

If you need to randomize (shuffle) the array content, you can use the method below to shuffle the array content after you initialize the array.

It can be used like so:

ItemParameter[] arr = {a,b,c,d,f,g,h};
ShuffleArr(arr);

The method:

public static void ShuffleArr<T>(T[] arr)
{  
    Random rng = new Random();  
    int n = arr.Length;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = arr[k];  
        arr[k] = arr[n];  
        arr[n] = value;
    }  
}
0

Something like this ?

    ItemParameter[] parameters = {a,b,c,d,f,g,h};
    ItemParameter tmp = new ItemParameter();
    tmp = parameters[5];
    parameters[5] = parameters[0];
    parameters[0] = tmp;
    tmp = parameters[6];
    parameters[6] = parameters[1];
    parameters[1] = tmp;