所以,我在一个列表中有一组整数
public List<int> numbers = new List<int>() { 3, 7, 6, 9, 8, 10, 11 }
我想要做的是改变这些数字,以便它们被排序在0到6之间,设置为siblingindexs。
然后就会变成
public List<int> newArrangedNumbers = new List<int>() {0, 2, 1, 4, 3, 5, 6}
但我真的不知道该怎么做。有人知道吗?
我不能重新排列数字,因为这样我就会忘记游戏对象,因为数字本身并不在数组中,但我在数组中有游戏对象,我找到每个游戏对象的"SortIndex“,这是上面的数字,数组中的数字的顺序实际上是数组中gameobjects的顺序,我需要保持相同的顺序。
编辑:我也不能将它们更改为浮动值,因为由于某种原因,在使用SetSiblingIndex(int)时,必须使用整数,不能使用浮点数。
编辑2:我不是试图对数字进行排序,而是按照顺序将数字从3-11转换为0-6。
发自:
{3, 7, 6, 9, 8, 10, 11}
至:
{0, 2, 1, 4, 3, 5, 6}
编辑3:这是我的测试脚本
List<int> Indexs = new List<int>() { 4, 7, 56, 9, 65, 67, 8, 3, 6 };
var sorted = Indexs.Select((x, i) => new KeyValuePair<int, int>(x, i)).OrderBy(x => x.Key).ToList();
List<int> newArrangedNumbers = sorted.Select(x => x.Value).ToList();
for(int i = 0; i < newArrangedNumbers.Count; i++)
{
Debug.Log(Indexs[i] + " : " + newArrangedNumbers[i]);
}
当我在“索引”列表中只有7 (0-6)个索引时,它工作得很好,但是当我再添加时,它开始给出错误的数字。
这就是它所给予的
发布于 2020-03-30 23:47:09
下面是一个很好的方法,可以从这个堆栈表单C# Sort list while also returning the original index positions?实现您想要的输出
解决方案的修改代码如下。
//The original list
List<int> numbers = new List<int>() { 3, 7, 6, 9, 8, 10, 11 };
var sorted = numbers
.Select((x, i) => new KeyValuePair<int, int>(x, i))
.OrderBy(x => x.Key)
.ToList();
//The sorted list
List<int> numbersSorted = sorted.Select(x => x.Key).ToList();
//List of indexes sorted based on the list above
List<int> newArrangedNumbers = sorted.Select(x => x.Value).ToList();
编辑
由于您排序列表,但也检索排序的索引,根据您刚刚排序的列表,您将不会有任何混淆您的游戏对象。
发布于 2020-03-31 00:03:52
听起来,您想要在相同项目的排序列表中找到每个元素的位置。
因此,对元素进行排序并找到元素所在的位置并分配索引。下面的代码示例假设是唯一的数字:
var sorted = numbers.OrderBy(x=>x).ToArray();
var result = new int[numbers.Count];
for (var i = 0; i < numbers.Count; i++)
{
var index = number.IndexOf(sorted[i]);
result[index] = i;
}
备注
IndexOf
。如果数字不是唯一的,或者性能很关键,则需要使用are的解决方案,即使很难理解,最终也会跟踪原始索引。https://stackoverflow.com/questions/60941257
复制相似问题