如何在 C# 中交换数组的两个值?

Nav*_*eer 3 .net c# arrays sorting swap

我有一个 int 数组,其中包含一些从索引 0 开始的值。我想交换两个值,例如索引 0 的值应该与索引 1 的值交换。如何在 c# 数组中执行此操作?

小智 13

使用元组

int[] arr = { 1, 2, 3 };
(arr[0], arr[1]) = (arr[1], arr[0]);
Console.WriteLine(string.Format($"{arr[0]} {arr[1]} {arr[2]}")); // 2 1 3
Run Code Online (Sandbox Code Playgroud)


Sea*_*ayn 10

如果你真的只想交换,你可以使用这个方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

x 和 y 是应该交换的指标。

如果你想与任何类型的数组交换,那么你可以这样做:

public static bool swap<T>(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;
}
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

string[] myArray = {"1", "2", "3", "4", "5", "6"};

if(!swap<string>(myArray, 0, 1)) {
    Console.WriteLine("x or y are out of range!");
    return;
}
Run Code Online (Sandbox Code Playgroud)

  • 在您的第一个示例中,“ref”是多余的(数组已经是引用)并且可能会生成次优代码。 (2认同)

MJG*_*MJG 9

您可以创建一个适用于任何数组的扩展方法

public static void SwapValues<T>(this T[] source, long index1, long index2)
{
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;
}
Run Code Online (Sandbox Code Playgroud)