Some notes on software development... RSS 2.0
# Friday, 11 September 2009

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:

image

Don’t forget that lists are zero-based ;-)

Friday, 11 September 2009 10:39:22 (GMT Standard Time, UTC+00:00)  #    -
C#
Navigation

Sign In
Extras
Statistics
Total Posts: 116
This Year: 0
This Month: 0
This Week: 0
Comments: 36
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2018
Hadrian Phillips

All Content © 2018, Hadrian Phillips
DasBlog theme 'Business' created by Christoph De Baene (delarou)