首页 > 解决方案 > 对双精度数组进行排序并返回原始索引的排序数组

问题描述

我想对一个双精度数组进行排序,但我想保存原始索引。我已经尝试了以下 -

double[] circs = new double[noOfCircs];

用值初始化 circs...

int[] loc = Enumerable.Range(0, noOfCircs-1).ToArray();
Array.Sort(circs, loc);

排序后,我想使用数组 loc 进行进一步的计算。我究竟做错了什么?

标签: c#asp.net.netsortingquicksort

解决方案


我建议在匿名类的帮助下使用Linq

using System.Linq;

...

double[] circs = ...

int[] loc = circs
  .Select((value, index) => new { // for each item we store
     value = value,               //   its value
     index = index                //   and original index
   })
  .OrderBy(pair => pair.value)  // Order by values
  .Select(pair => pair.index)   // By return original index
  .ToArray();

推荐阅读