C# 在c中,根据元素大小对数组排序并返回数组索引#
我需要对数组从最小值到最大值进行排序,但排序后只需要返回数组的索引。我不想交换值,我只需要根据值大小返回值索引, 例如C# 在c中,根据元素大小对数组排序并返回数组索引#,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我需要对数组从最小值到最大值进行排序,但排序后只需要返回数组的索引。我不想交换值,我只需要根据值大小返回值索引, 例如 int[]arr={7,8,2,3,1,5}; 对于(int i=0;i您在for循环中的检查是错误的,它应该是i
int[]arr={7,8,2,3,1,5};
对于(int i=0;i您在for循环中的检查是错误的,它应该是i
。对于索引,您可以执行以下操作:
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();
对于输出:
foreach(int item in sortedIndexArray)
Console.WriteLine(item);
输出:
4
2
3
5
0
1
您在for循环中的检查错误,它应该是i
。对于索引,您可以执行以下操作:
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();
对于输出:
foreach(int item in sortedIndexArray)
Console.WriteLine(item);
输出:
4
2
3
5
0
1
我使用的是名称-值集合,我尝试使用getvalue从中获取值,比较它们,然后根据大小返回索引。@user2345759,您的示例是int数组。我想您可以在集合中实现类似的功能。我使用的是名称-值集合,我尝试使用getvalue,比较它们,然后根据大小返回索引。@user2345759,您的示例是int数组。我想您可以在集合中实现类似的功能。