Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

indexing - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...