c# - 使用 lambda 重新排列 List<T>

标签 c# list lambda

我需要重新排列项目列表,以便所选项目进入列表末尾,最后一项替换前一项,前一项替换之前的项目,依此类推。

例如,如果我有一个包含 10 个项目的列表,并且所选项目位于位置 5,则该项目转到位置 9,9 将替换 8,然后 8 替换 7,7 替换 6,6 占据位置 5。我成功了使用此代码获得所需的结果:

List<int> numList = new List<int>();
int selectedNum = 5;//Selected at runtime
for (int i = 0; i < 10; i++) numList.Add(i);
int numListCount = numList.Count-1;
int tempNum = numList[numListCount];
List<int> tempList = numList.GetRange(selectedNum + 1,(numList.Count-selectedNum) - 2);
numList[numListCount] = selectedNum;
numList.RemoveRange(selectedNum, (numList.Count-selectedNum)-1);
numList.InsertRange(selectedNum, tempList);
numList.Insert(numListCount - 1, tempNum);

结果是:

0,1,2,3,4,6,7,8,9,5

我确定我的代码丑陋且效率低下:我有两个问题:

  1. 是否有可能使用 Lambda 获得相同的结果?如果不能,则
  2. 我怎样才能改进我的代码。谢谢。

最佳答案

您可以使用 Remove Method删除所选项目和 Add Method将其附加在末尾:

List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);

int selectedNum = 6; // selected at runtime
numList.Remove(selectedNum);
numList.Add(selectedNum);

之前:

0 2 4 6 8 10 12 14 16 18

删除后(6):

0 2 4 8 10 12 14 16 18

添加后(6):

0 2 4 8 10 12 14 16 18 6

如果你想移动选定索引处的项目,你可以使用 RemoveAt Method而不是 Remove Method :

List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);

int selectedIndex = 5; // selected at runtime
int selectedNum = numList[selectedIndex];
numList.RemoveAt(selectedIndex);
numList.Add(selectedNum);

之前:

0 2 4 6 8 10 12 14 16 18

在 RemoveAt(5) 之后:

0 2 4 6 8 12 14 16 18

添加 (10) 后:

0 2 4 6 8 12 14 16 18 10

使用 LINQ,您将创建一个新列表,其中删除并附加了所选项目。不过,如上所示的就地更新效率要高得多。

List<int> numList = new List<int>();
for (int i = 0; i < 10; i++) numList.Add(2 * i);

int selectedIndex = 5; // selected at runtime
List<int> newNumList = numList.Take(selectedIndex)
                              .Concat(numList.Skip(selectedIndex + 1))
                              .Concat(numList.Skip(selectedIndex).Take(1))
                              .ToList();

numList:

0 2 4 6 8 10 12 14 16 18

新数字列表:

0 2 4 6 8 12 14 16 18 10

关于c# - 使用 lambda 重新排列 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7351558/

相关文章:

java - 多次打乱列表

c# - 使用 LINQ 和 Entity Framework 检查 c# var 中的空值

C++ 11 binary_search 和 lambda 函数用例

c# - 使用不同大小的像素着色器采样器创建 WPF 效果

c# - C++ vector 与C#列表。他们为什么产生不同的结果?

c# - .NET 4.0 中的 WebHttpBinding?

r - 理解 c( ) 对命名向量的影响

c# - 自建的Node <T>\List <T>类到系统节点和列表之间的C#模糊引用

c++ - boost 与 vector 成员函数的绑定(bind)

c# - 为什么LINQ操作会丢失集合的静态类型?