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
110 views
in Technique[技术] by (71.8m points)

c# - Sort one List<> based on another

Say I have

List<int> ages  = new List<int>() { 8, 5, 3, 9, 2, 1, 7 };
List<int> marks = new List<int>() { 12, 17, 08, 15, 19, 02, 11 };

I can sort my marks by ages like this:

while (true)
{
  bool swapped = false;

  for (int i = 0; i < ages.Count - 1; i++)
    if (ages[i] > ages[i + 1])
    {
      int tmp = ages[i];
      ages[i] = ages[i + 1];
      ages[i + 1] = tmp;

      tmp = marks[i];
      marks[i] = marks[i + 1];
      marks[i + 1] = tmp;

      swapped = true;
    }

  if (!swapped)
    break;
}

Now I want to put this into a function that accepts any two lists. The first parameter will be the reference list, the numerical or comparable list. The second parameter will be the list containing the data.

For example:

public static void Sort<T>(List<T> RefList, List<T> DataList)
{
  // sorting logic here...
}

There are a few problems:

First of all, T is almost certainly not the same type in RefList and DataList. RefList might be dates, integers, or doubles; whereas DataList is free to be absolutely anything. I need to be able to receive two, arbitrary generic types.

Secondly, I cannot seem to use the > operator with the T in this line:

if (ages[i] > ages[i + 1])

Perhaps my whole approach is wrong.

By the way, I have read responses to similar questions that suggest that the two lists should be combined into a single list of a compound data type. This isn't practical at all for my application. All I want to do is write a static function that somehow sorts one list based on the elements of another.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There's no framework method to do this with List<T>, but if you don't mind putting the data into two arrays, you can use one of the Array.Sort() overloads that takes two arrays as arguments. The first array is the keys, and the second is the values, so your code might look like this (leaving aside the step of getting arrays from the lists):

Array.Sort(ages, marks);

The specifics of getting the values into arrays and then back into lists would depend, among other things, on whether you need to end up with the same list sorted appropriately or whether it's okay to return a new list with the data in the desired order.


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

...