A buddy of mine suddenly popped me a question, how to sort a list of string according to the substring, this is a very good question, as I’ve never come across this kind of sorting, usually will use the Array.Sort or Array.Reverse to handle the thing. But to sort according to the substring is something new to me.
To do that, we’ll need the ICompare interface. In this scenario, I got an array that looks like this:
string[] s = { "aaaB", "aacC", "aabA" };
which will give the result of aaaB, aabA, aacC if using the Array.Sort. Now the objective is to sort the list based on the last character, but not the other. To do this, I’ve use a class that implement ICompare (I’m doing it for .NET 1.1, I don’t have fancy lambda or maybe I just don’t know how to do it without class).
class Comparing: IComparer
{
public int Compare(object x, object y)
{
return String.Compare(x.ToString().Substring(3), y.ToString().Substring(3));
}
}
We’ll need the System.Collections namespace for this, the only function inside this class is the implementation of the IComparer interface, which is a required function. The function compare 2 value, x and y, which will be our array item.
Here I using the substring of each x and y to get the last character that I wanted to sort, and compare them with String.Compare. To call our class,
string[] s = { "aaaB", "aacC", "aabA" };
Array.Sort(s, new Comparing());
foreach(string str in s)
{
Console.WriteLine(str);
}
By just passing in our new class in the Array.Sort, now it work out very well. 😀