Reverse elements in an array

后端 未结 6 1888
既然无缘
既然无缘 2020-11-30 14:58

I setup an array and i would like to create a method that will return an array with the elements in reverse. e.g. if there are 10 slots then array1[9] = 6 so

6条回答
  •  时光说笑
    2020-11-30 15:42

    You should be able to use the extension method Reverse

    int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
    Console.WriteLine("Before");
    PrintArray(arr);
    Console.WriteLine("After");
    PrintArray(arr.Reverse().ToArray());
    

    Or if you don't mind modifing the original sequence you can use Array.Reverse

    int[] arr = { 43, 22, 1, 44, 90, 38, 55, 32, 31, 9 };
    Console.WriteLine("Before");
    PrintArray(arr);
    Array.Reverse(arr);
    Console.WriteLine("After");
    PrintArray(arr);
    

提交回复
热议问题