简体   繁体   English

根据c#中的元素大小对数组进行排序并返回数组的索引

[英]Sort an array and return index of arrays according to elements size in c#

I need to sort the array from minimum to maximum value, but I need to return only the index of array after sorting it. 我需要将数组从最小值到最大值进行排序,但是我需要在对数组进行排序之后仅返回数组的索引。 I dont want to swap values, I just need to return the values index according to the value size, for eg 我不想交换值,我只需要根据值的大小返回值索引,例如

int[] arr = {7,8,2,3,1,5};
for (int i=0; i<=arr.length; i++)
{
   int index = Array.IndexOf(arr, i);
}

Now I want to return index of values from minimum to maximum as 4,2,3,5,0,1. 现在,我想返回值的索引,从最小值到最大值分别为4,2,3,5,0,1。

Your check in the for loop is wrong it should be i < arr.Length . 您在for循环中签入错误,应该是i < arr.Length For index you can do: 对于索引,您可以执行以下操作:

int[] arr = { 7, 8, 2, 3, 1, 5 };
int[] sortedIndexArray = arr.Select((r, i) => new { Value = r, Index = i })
                            .OrderBy(t => t.Value)
                            .Select(p => p.Index)
                            .ToArray();

For output: 对于输出:

foreach(int item in sortedIndexArray)
    Console.WriteLine(item);

Output: 输出:

4
2
3
5
0
1
var indexes = arr.Select((i, inx) => new { i, inx })
                  .OrderBy(x => x.i)
                  .Select(x => x.inx)
                  .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM