使用lambda重新排列List <t> </t>

时间:2011-09-08 16:40:59

标签: 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. 如何优化我的代码。感谢。

4 个答案:

答案 0 :(得分:8)

您可以使用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

newNumList:

0 2 4 6 8 12 14 16 18 10

答案 1 :(得分: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)。如果您知道该值,则发布的其他答案是正确的

答案 2 :(得分:1)

你不需要包括临时列表在内的所有额外内容。你可以做到

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

这很简单。

答案 3 :(得分:0)

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

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