使用 LINQ 与 c# 交换 List<> 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1111018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swap List<> elements with c# using LINQ
提问by
I have this list
我有这个清单
var list = new List { 3, 1, 0, 5 };
var list = new List { 3, 1, 0, 5 };
I want to swap element 0 with 2
我想用 2 交换元素 0
output 0, 1, 3, 5
输出 0、1、3、5
采纳答案by Reed Copsey
If you just want it sorted, I'd use List.Sort().
如果你只是想让它排序,我会使用 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);
回答by Matthew Groves
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.
如果这就是您要找的,我认为 Linq 没有任何“交换”功能。
回答by Andrew Siemer
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).
看看“扩展方法”的概念。有了这个,您可以轻松地使您的列表支持 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;
}
}
}