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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With