Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom sorting of a string array in C#

Tags:

arrays

c#

I have a string array or arraylist that is passed to my program in C#. Here is some examples of what those strings contain:

"Spr 2009" "Sum 2006" "Fall 2010" "Fall 2007"

I want to be able to sort this array by the year and then the season. Is there a way to write a sorting function to tell it to sort by the year then the season. I know it would be easier if they were separate but I can't help what is being given to me.

like image 802
Scott Chantry Avatar asked Aug 30 '25 18:08

Scott Chantry


1 Answers

You need to write a method which will compare any two strings in the appropriate way, and then you can just convert that method into a Comparison<string> delegate to pass into Array.Sort:

public static int CompareStrings(string s1, string s2)
{
    // TODO: Comparison logic :)
}
...

string[] strings = { ... };
Array.Sort(strings, CompareStrings);

You can do the same thing with a generic list, too:

List<string> strings = ...;
strings.Sort(CompareStrings);
like image 115
Jon Skeet Avatar answered Sep 02 '25 06:09

Jon Skeet