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

8

我有一个包含一些值的整数数组,起始索引为0。我想要交换两个值,例如,索引0处的值应该与索引1处的值交换。怎样才能在C#数组中实现这个功能?

7个回答

36

使用一个 元组(tuple)

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

元组在 C# 7.0 中可用。请参阅 Tuple types (C# reference)


12
您可以创建一个扩展方法,适用于任何数组:
public static void SwapValues<T>(this T[] source, long index1, long index2)
{
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;
}

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 temp = array[x];
        array[x] = array[y];
        array[y] = temp;    


        return true;
}

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 temp = objectArray[x];
        objectArray[x] = objectArray[y];
        objectArray[y] = temp ;
        

        return true;
}

你可以这样调用它:

string[] myArray = {"1", "2", "3", "4", "5", "6"};
        
if(!swap<string>(myArray, 0, 1)) {
    Console.WriteLine("x or y are out of range!");
}
else {
    //print myArray content (values will be swapped)
}

2

只想交换两个值一次或者想对整个数组进行相同操作:

假设您只想交换两个值一次,且这些值是整数类型,则可以尝试以下方法:

    int temp = 0;
    temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;

1

可以通过XOR运算符(数学魔术)交换两个值,如下所示:

public static void Swap(int[] a, int i, int k)
{
    a[i] ^= a[k];
    a[k] ^= a[i];
    a[i] ^= a[k];
}

这是XOR交换算法 - Peter Mortensen

1
static void SwapInts(int[] array, int position1, int position2)
{      
    int temp = array[position1]; // Copy the first position's element
    array[position1] = array[position2]; // Assign to the second element
    array[position2] = temp; // Assign to the first element
}

调用这个函数并打印元素


1
我刚写了类似的东西,所以这里有一个版本:
  • 使用泛型,因此可以适用于int、string等等;
  • 使用扩展方法;
  • 带有测试类。
祝使用愉快 :)
[TestClass]
public class MiscTests
{
    [TestMethod]
    public void TestSwap()
    {
        int[] sa = {3, 2};
        sa.Swap(0, 1);
        Assert.AreEqual(sa[0], 2);
        Assert.AreEqual(sa[1], 3);
    }
}

public static class SwapExtension
{
    public static void Swap<T>(this T[] a, int i1, int i2)
    {
        T t = a[i1]; 
        a[i1] = a[i2]; 
        a[i2] = t; 
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接