[英]Swap List<> elements with c# using LINQ
我有這個清單
var list = new List {3,1,0,5};
我想用2交換元素0
輸出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有任何'交換'功能,如果這是你正在尋找的。
在沒有直接支持的情況下......讓它成為第1名!
看看“擴展方法”的概念。 通過這種方式,您可以輕松地使列表支持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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.