Here is an extension method that will swap two list items for any class that implements IList
public static void SwapElements<T>(this IList<T> obj, int index1, int index2)
{
if (index1 > (obj.Count() - 1) ||
index2 > (obj.Count() - 1) ||
index1 < 0 || index2 < 0)
{
throw (new IndexOutOfRangeException());
}
T tempHolder = obj[index1];
obj[index1] = obj[index2];
obj[index2] = tempHolder;
}
And a quick test:
static void Main(string[] args)
{
List<string> testList = new List<string>();
testList.AddRange(new string[] { "Test1", "Test2", "Test3", "Test4", "Test5" });
Console.WriteLine("Original List Contents");
testList.ForEach(s => Console.WriteLine("{0}", s));
testList.SwapElements(1, 3);
Console.WriteLine(Environment.NewLine);
Console.WriteLine("Swapped Item 1 with 3 List Contents");
testList.ForEach(s => Console.WriteLine("{0}", s));
Console.ReadLine();
}
The result:
Don’t forget that lists are zero-based 