简体   繁体   中英

c# how to sort 2D array values

I have 2 arrays

string[,] marksMatrix = new string[5, 4];
string[] studentIDArr = new string[5];

Marks matrix has the marks of 5 students for 4 subjects and their student IDs are stored in the studentIDArr. When I display the student IDs and marks of each student, how do I sort it in ascending order of the student IDs?

textBox2.Text = "StudentID\tOOAD\tDWA\tDB\tWAD\r\n";
int rowlength = marksMatrix.GetLength(0);
int collength = marksMatrix.GetLength(1);

for (int y = 0; y < rowlength; y++) {
  textBox2.Text += studentIDArr[y];
  for (int x = 0; x < collength; x++) {
    textBox2.Text += "\t" + marksMatrix[y,x];
  }
  textBox2.Text += "\r\n";
}

A possible solution is:

  1. Declare a new vector of strings (let's call it studentIDArrSorted)
  2. Sort studentIDArr and store it in studentIDArrSorted, without altering the order of studentIDArr.
  3. Now take a for on studentIDArrSorted
  4. For studentIDArrSorted[i], search is position in studentIDArr.
  5. Print the corresponding column from marksMatrix.

Example: Initial list : "3", "4", "2"
Sorted list: "2", "3", "4"

The old position of "2" in list was 3, so you must print the 3th line from the matrix.
Note: I assume that the ids are unique.

A more simple solution will be to store the both arrays (the marks and the ids) in an object. This will get rid of all the overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM