You need give an order (actually a equivalence relation) to be able to sort. The order on characters is usually a,b,c,… and the order usually given on words such as ‘one’ is called lexicographic order. However you want to sort by the meaning behind, its semantic: integers.
Your computer doesn’t know that you want this, so you need to provide the meaning., which is through a function (technically a dictionary).
Computers have order on integers builtin (it’s also builtin in standard integers, in usual mathematics). Hence you need to provide a one-to-one function (eg., with a dictionary, or a list of uples eg., List<(string, int)>), so you sort your words from their integer peer. You can also map words with letters: one-a, two-b, … and when you reach z, you continue with aa (it’s a base 27 counting). You can also do this with bits (base 2), base64, etc. But there is always a map with integers.
IMHO, understanding is more important than knowing. Now you can code many solutions.
You can store numbers in a dictionary where the keys would be strings (e.g. "two"
) and the values would be integers (e.g. 2
). And by using LINQ you could first replace the strings in your input array with numbers and then sort them with OrderBy
. After the numbers are sorted you can convert the numbers back to strings:
Dictionary<string, int> numbers = new Dictionary<string, int>() {
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 },
{ "six", 6 },
{ "seven", 7 },
{ "eight", 8 },
{ "nine", 9 },
};
string[] wordArray = { "two", "three", "one", "seven", "nine", "two", "one" };
var numberArray = Enumerable.Range(0, wordArray.Length)
.Select(i => numbers[wordArray[i]])
.OrderBy(x => x).ToArray();
var output = Enumerable.Range(0, numberArray.Length)
.Select(i => numbers.FirstOrDefault(x => x.Value == numberArray[i]).Key)
.ToArray();
Output
= {"one","one","two","two","three","seven","nine"}