Is there a LINQ way to swap the position of two items inside a List<T>
?
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.
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.
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);
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With