(C#) Swap two items in a generic list

By | June 24, 2013

Put this in a static class. This will apply to Lists of any type.

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
	if (indexB > -1 && indexB < list.Count)
		T tmp = list[indexA];
		list[indexA] = list[indexB];
		list[indexB] = tmp;
	return list;

Simply call it like this

myList.Swap(indexA, indexB);

Leave a Reply

Your email address will not be published. Required fields are marked *