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

后端 未结 6 563
情话喂你
情话喂你 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:19

    I just wrote something similar, so here is a version that

    • uses generics so that it works on ints, strings etc,
    • uses extension methods
    • comes with a test class

    Enjoy :)

    [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(this T[] a, int i1, int i2)
        {
            T t = a[i1]; 
            a[i1] = a[i2]; 
            a[i2] = t; 
        }
    }
    

提交回复
热议问题