Swap two items in a List in C#
This post will discuss how to swap two items in a List in C#.
We can easily write an extension method to swap an element of the list with another element. For example, consider the following code, which swaps the element at index 2 with the element at index 3 in the list using a temporary variable.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Collections.Generic; public static class Extensions { public static void Swap<T>(this List<T> list, int i, int j) { T temp = list[i]; list[i] = list[j]; list[j] = temp; } } public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.Swap(2, 3); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 4, 3, 5 } } |
Note that the extension method needs to go inside a static class. Alternatively, you can simply write:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; public static class Extensions { public static void Swap<T>(this List<T> list, int i, int j) { (list[i], list[j]) = (list[j], list[i]); } } public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; nums.Swap(2, 3); Console.WriteLine(String.Join(", ", nums)); // 1, 2, 4, 3, 5 } } |
That’s all about swapping two items in a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)