【发布时间】:2009-07-10 17:51:58
【问题描述】:
我有这份清单
var list = new List { 3, 1, 0, 5 };
我想将元素 0 与 2 交换
输出 0、1、3、5
【问题讨论】:
我有这份清单
var list = new List { 3, 1, 0, 5 };
我想将元素 0 与 2 交换
输出 0、1、3、5
【问题讨论】:
如果您只想对其进行排序,我会使用 List.Sort()。
如果你想交换,没有内置的方法可以做到这一点。不过,编写扩展方法会很容易:
static void Swap<T>(this List<T> 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 没有任何“交换”功能。
【讨论】:
如果某些东西不被直接支持......让它成为第一!
看看"extension methods"的概念。有了这个,您可以轻松地使您的列表支持 Swap() 的概念(这适用于您想要扩展类的功能的任何时候)。
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;
}
}
}
【讨论】: