如何移动列表末尾的列表对象,同时转移其他列表对象? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

首先,我必须说我已经花了一整天的时间来搜索我的答案,然后才在这里发布这个问题。我得到的最接近的答案是here,但有些答案对我不起作用,而其他答案对我来说太复杂了。让我清楚地解释一下我想要实现的目标:为简单起见,我想我有一个由“6”对象组成的列表。我在列表中随机选择一个索引,比如myList [index = 2]。然后我希望这个对象位于列表的末尾,这意味着它的索引值现在为5.此外,我想重新排列未触摸的对象,以获得相同大小的列表而没有空索引值。完成所有这些步骤后,它应该是这样的:

ListOrder

目前我的代码是这样的:

 public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
 {
     if ((oldIndex == newIndex) || (0 > oldIndex) || (oldIndex >= list.Count) || (0 > newIndex) ||
         (newIndex >= list.Count)) return;
     // local variables
     var i = 0;
     T tmp = list[oldIndex];
     for (i = oldIndex+1; i < newIndex; i++)
     {
         list[i] = list[i - 1];
     }        
     list[newIndex] = tmp;
 }  

但是,正如您可以预测它不起作用。 Debug.DrawLine到这个列表中的gameobjects显示我当我通过列表移动项目时,我的代码留下了两个对象myList [0]和一个myList [5]我添加了。其他线路消失后。

c# arrays list sorting unity3d
1个回答
4
投票

你是在思考这个问题。

var value = list[index];
list.RemoveAt(index);
list.Add(value);
© www.soinside.com 2019 - 2024. All rights reserved.