I have this list
var list = new List { 3, 1, 0, 5 };
I want to swap element 0 with 2
output 0, 1, 3, 5
I have this list
var list = new List { 3, 1, 0, 5 };
I want to swap element 0 with 2
output 0, 1, 3, 5
Classic swap is...
int temp = list[0];
list[0] = list[2];
list[2] = temp;
I don't think Linq has any 'swap' functionality if that's what you're looking for.
I don't think that's possible in LINQ... or at the very least, it's silly to do it in LINQ.
void Swap(List list, int a, int b)
{
int temp = list[a];
list[a] = list[b];
list[b] = temp;
}
If you just want it sorted, I'd use List.Sort().
If you want to swap, there is no built in method to do this. It'd be easy to write an extension method, though:
static void Swap<T>(this List<T> list, int index1, int index2)
{
T temp = list[index1];
list[index1] = list[index2];
list[index2] = temp;
}
You could then do:
list.Swap(0,2);
In the case that something is not directly supported ...make it so number 1!
Take a look at the concept of "extension methods". With this you can easily make your list support the concept of Swap() (this applies to any time you want to extend the functionality of a class).
namespace ExtensionMethods
{
//static class
public static class MyExtensions
{
//static method with the first parameter being the object you are extending
//the return type being the type you are extending
public static List<int> Swap(this List<int> list,
int firstIndex,
int secondIndex)
{
int temp = list[firstIndex];
list[firstIndex] = list[secondIndex];
list[secondIndex] = temp;
return list;
}
}
}