How can I swap two values of an array in c#?

后端 未结 6 507
情话喂你
情话喂你 2021-01-17 06:45

I have an array of int containing some values starting from index 0. I want to swap two values for example value of index 0 should be swapped with the value of index 1. How

6条回答
  •  醉梦人生
    2021-01-17 07:27

    If you really only want to swap, you can use this method:

    public static bool swap(int x, int y, ref int[] array){
    
            // check for out of range
            if(array.Length <= y || array.Length <= x) return false;
    
    
            // swap index x and y
            var buffer = array[x];
            array[x] = array[y];
            array[y] = buffer;  
    
    
            return true;
    }
    

    x and y are the indizies, that should be swapped.

    If you want to swap with any type of array, then you can do it like this:

    public static bool swap(this T[] objectArray, int x, int y){
    
            // check for out of range
            if(objectArray.Length <= y || objectArray.Length <= x) return false;
    
    
            // swap index x and y
            T buffer = objectArray[x];
            objectArray[x] = objectArray[y];
            objectArray[y] = buffer;
    
    
            return true;
    }
    

    And you can call it like:

    string[] myArray = {"1", "2", "3", "4", "5", "6"};
    
    if(!swap(myArray, 0, 1)) {
        Console.WriteLine("x or y are out of range!");
        return;
    }
    

提交回复
热议问题