I have this very simple array which I want to be able to move around some items in. Are there any built in tools in c# to do this? If not, du you have any suggestion in how
This 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
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();
}
}
}
EDIT: Okay, now you've changed the example, there's nothing built-in - and it would actually be a bit of a pain to write... you'd need to consider cases where you're moving it "up" and where you're moving it "down", for example. You'd want unit tests, but I think this should do it...
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;
}
You should probably consider using a List<T>
instead of an array, which allows you to insert and remove at particular indexes. Those two operations will be more expensive than only copying the relevant section, but it'll be a lot more readable.
It's an existing question:
C# Array Move Item (Not ArrayList/Generic List)
The answer is:
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);
}