String to Array, Sort by 3rd Word/Column

Viewed 113

I have a string with numbers, words, and linebreaks that I split into an Array.

If I run Array.Sort(lines) it will sort the Array numerically by Column 1, Number.

How can I instead sort the Array alphabetically by Column 3, Color?


Note: They are not real columns, just spaces separating the words.

I cannot modify the string to change the results.


| Number     | Name       | Color      |
|------------|------------|------------|
| 1          | Mercury    | Gray       |
| 2          | Venus      | Yellow     |
| 3          | Earth      | Blue       |
| 4          | Mars       | Red        |

C#

Example: http://rextester.com/LSP53065

string planets = "1 Mercury Gray\n"
               + "2 Venus Yellow\n"
               + "3 Earth Blue\n"
               + "4 Mars Red\n";


// Split String into Array by LineBreak
string[] lines = planets.Split(new string[] { "\n" }, StringSplitOptions.None);


// Sort
Array.Sort(lines);


// Result
foreach(var line in lines)
{
    Console.WriteLine(line.ToString());
}

Desired Sorted Array Result

3 Earth Blue
1 Mercury Gray
4 Mars Red
2 Venus Yellow
3 Answers
Related