Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two items in List<T>

Tags:

c#

linq

swap

Is there a LINQ way to swap the position of two items inside a List<T>?

like image 679
Tony The Lion Avatar asked Jan 19 '10 14:01

Tony The Lion


People also ask

How to swap 2 elements in a list java?

In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.

How do you swap two elements?

The standard solution to swap two elements in a List is using the Collections. swap() method, which swaps the elements at the specified positions in a list.


2 Answers

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB) {     T tmp = list[indexA];     list[indexA] = list[indexB];     list[indexB] = tmp; } 

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB) {     T tmp = list[indexA];     list[indexA] = list[indexB];     list[indexB] = tmp;     return list; } 

var lst = new List<int>() { 8, 3, 2, 4 }; lst = lst.Swap(1, 2); 
like image 87
Jan Jongboom Avatar answered Sep 19 '22 18:09

Jan Jongboom


Maybe someone will think of a clever way to do this, but you shouldn't. Swapping two items in a list is inherently side-effect laden but LINQ operations should be side-effect free. Thus, just use a simple extension method:

static class IListExtensions {     public static void Swap<T>(         this IList<T> list,         int firstIndex,         int secondIndex     ) {         Contract.Requires(list != null);         Contract.Requires(firstIndex >= 0 && firstIndex < list.Count);         Contract.Requires(secondIndex >= 0 && secondIndex < list.Count);         if (firstIndex == secondIndex) {             return;         }         T temp = list[firstIndex];         list[firstIndex] = list[secondIndex];         list[secondIndex] = temp;     } } 
like image 21
jason Avatar answered Sep 17 '22 18:09

jason