使用LINQ使用c#交换List 元素
我有这个清单
var list = new List {3,1,0,5};
我想用2交换元素0
输出0,1,3,5
如果你只是想要它排序,我会使用List.Sort()。
如果要交换,则没有内置方法来执行此操作。 但是编写扩展方法很容易:
static void Swap(this List list, int index1, int index2) { T temp = list[index1]; list[index1] = list[index2]; list[index2] = temp; }
然后你可以这样做:
list.Swap(0,2);
经典互换是……
int temp = list[0]; list[0] = list[2]; list[2] = temp;
我不认为Linq有任何’交换’function,如果这是你正在寻找的。
在没有直接支持的情况下……让它成为1号!
看看“扩展方法”的概念。 通过这种方式,您可以轻松地使列表支持Swap()的概念(这适用于您希望扩展类function的任何时间)。
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 Swap(this List list, int firstIndex, int secondIndex) { int temp = list[firstIndex]; list[firstIndex] = list[secondIndex]; list[secondIndex] = temp; return list; } } }