使用 Lambda 表达式对 List<T> 进行重新排序

6
我需要重新排列一个项目列表,使所选项目移到列表末尾,最后一个项目替换前一个项目,前一个项目替换它之前的项目,以此类推。
例如,如果我有一个包含十个项目的列表,并且所选项目位于第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. 我该如何改进我的代码。谢谢。
4个回答

8
您可以使用Remove 方法来删除所选项,使用Add 方法将其附加到结尾:
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 方法而不是Remove 方法

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();

数字列表:

0 2 4 6 8 10 12 14 16 18

newNumList:

0 2 4 6 8 12 14 16 18 10

1

从我的理解来看,您只是想将给定的项目移动到列表底部,对吗?

List<int> list = new List<int>();
for (int i = 0; i < 10; i++) 
    numList.Add(i);
int temp = list[5];
list.RemoveAt(5);
list.Add(temp);

编辑:我的理解是您知道要移动的项目的位置(5)。如果您知道该值,则另一个发布的答案是正确的。


1

你不需要那么多额外的东西,包括一个临时列表。你可以直接这样做

numList.Remove(selectedNum);
numList.Add(selectedNum);

就是这么简单。


0

现在无法检查,但这应该可以解决问题:

var temp = list.Take(index-1).Concat(list.Skip(index)).Concat(list[index]);
list = temp;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接