Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there C# support for an index-based sort?

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.

I am using C#.NET 3.5, under Windows.

like image 421
Mark T Avatar asked Mar 18 '09 19:03

Mark T


1 Answers

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]));
like image 195
Guffa Avatar answered Oct 23 '22 05:10

Guffa