(C#) Swap two items in a generic list


Put this in a static class. This will apply to Lists of any type.
[c language=”language="#”]
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;
}
[/c]

Simply call it like this
[c language=”language="#”]
myList.Swap(indexA, indexB);
[/c]

Leave a Reply

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