English 中文(简体)
是否有支持索引排序的C#支持?
原标题:
  • 时间:2009-03-18 19:58:47
  •  标签:

Is there any built-in C# support for doing an index sort?

More Details:
I have several sets of data stored in individual generic Lists of double. These are lists always equal in length, and hold corresponding data items, but these lists come and go dynamically, so I can t just store corresponding data items in a class or struct cleanly. (I m also dealing with some legacy issues.)

I need to be able to sort these keyed from any one of the data sets.

My thought of the best way to do this is to add one level of indirection, and use an index based sort. Such sorts have been in use for years.

Quick definition of index based sort :
make "index", an array of consecutive integers the same length as the lists, then the sort algorithm sorts the list of integers so that anylist[index[N]] gives the Nth item of anylist in sorted order. The lists themselves are never re-ordered.

Is there any built-in C# support for doing an index sort? I have been unable to find it... everything I have found reorders the collection itself. My guess is support exists but I haven t looked in the right place yet.

我在windows下使用C#.NET 3.5。

最佳回答

Once you have set up the index array, you can sort it using a custom Comparison<T> that compares the values in the corresponding items in the data array:

Array.Sort<int>(index, (a,b) => anylist[a].CompareTo(anylist[b]));
问题回答

以下代码实现了索引排序。注意ToArray()调用以克隆数据数组。如果省略,数据数组也会被排序。

static void Main(String[] args)
{
   Int32[] data = new Int32[] { -6, 6, 5, 4, 1, 2, 3, 0, -1, -2, -3, -4, -5 };

   Int32[] indices = Enumerable.Range(0, data.Length).ToArray();

   Array.Sort(data.ToArray(), indices);

   foreach (Int32 index in indices)
   {
       Console.Write(String.Format("{0} ", data[index]));
   }

   Console.ReadLine();
}

输出结果符合预期。

-6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6




相关问题
热门标签