Moving elements in a C # array

I have this very simple array that I want to be able to move some elements. Are there any built-in tools in C # for this? If not, do you have any suggestion on how to do this.

In the example

var smallArray = new string[4];
smallArray[0] = "a";
smallArray[1] = "b";
smallArray[2] = "c";
smallArray[3] = "d";

And let's say I want to (programmatically) shift index 2 and 0 by creating

smallArray[0] = "c";
smallArray[1] = "a";
smallArray[2] = "b";
smallArray[3] = "d";

Thank.

+5
source share
4 answers

EDIT: Okay, now you have changed the example, there is nothing built-in - and it would actually be a little painful to write ... you will need to consider cases where you move it up and where you move it down, for example. You need unit tests, but I think this should be done ...

public void ShiftElement<T>(this T[] array, int oldIndex, int newIndex)
{
    // TODO: Argument validation
    if (oldIndex == newIndex)
    {
        return; // No-op
    }
    T tmp = array[oldIndex];
    if (newIndex < oldIndex) 
    {
        // Need to move part of the array "up" to make room
        Array.Copy(array, newIndex, array, newIndex + 1, oldIndex - newIndex);
    }
    else
    {
        // Need to move part of the array "down" to fill the gap
        Array.Copy(array, oldIndex + 1, array, oldIndex, newIndex - oldIndex);
    }
    array[newIndex] = tmp;
}

, List<T> , . , , .

+12

:

# ( ArrayList/ )

:

void MoveWithinArray(Array array, int source, int dest)
{
  Object temp = array.GetValue(source);
  Array.Copy(array, dest, array, dest + 1, source - dest);
  array.SetValue(temp, dest);
}
+5

It solved my problem

var arr = new ArrayList 
    {
        "a", "b", "c", "d", "e", "f"
    };
var first = arr[2];  //pass  the value which you want move from 
var next = arr[5]; //pass the location where you want to place
var m = 0;
var k = arr.IndexOf(first, 0, arr.Count);
m = arr.IndexOf(next, 0, arr.Count);
if (k > m)
{
    arr.Insert(m, first);
    arr.RemoveAt(k + 1);
}
else
{
    arr.Insert(k, next);
    arr.RemoveAt(m + 1);
}

returns a, b, f, c, d, e

0
source
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SecondLargest
{
    class ArraySorting
    {
        public  static void Main()
        {
         int[] arr={5,0,2,1,0,44,0,9,1,0,23};

         int[] arr2 = new int[arr.Length];
         int arr2Index = 0;
         foreach (int item in arr)
         {
           if(item==0)
           {
               arr2[arr2Index] = item;
               arr2Index++;
           }
         }
         foreach (int item in arr)
         {
            if(item!=0)
            {
                arr2[arr2Index] = item;
                arr2Index++;
            }
         }

         foreach (int item in arr2)
         {
             Console.Write(item+" ");
         }

            Console.Read();

        }
    }
}
0
source

All Articles