Custom sorting of a string array in 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 开发者_StackOverflow中文版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);
You could split the strings by the space character, convert both parts to integers and then use LINQ:
string[] seasons = new[] { "Spr", "Sum", "Fall", "Winter" };
string[] args = new[] { "Spr 2009", "Sum 2006", "Fall 2010", "Fall 2007" };
var result = from arg in args
let parts = arg.Split(' ')
let year = int.Parse(parts[1])
let season = Array.IndexOf(seasons, parts[0])
orderby year ascending, season ascending
select new { year, season };
You could always separate them. Create name-value-value triplets and work with them like that. Use Left and Right string functions if the data is formatted consistently. Then you sort on the year part first, and then the season part. Although Jon's idea seems really good, this is one idea of what to put in that method.
I believe what you're looking for is the StringComparer class.
var strings = new string[] {"Spr 2009", "Sum 2006", "Fall 2010", "Fall 2007"};
var sorted = strings.OrderBy(s =>
{
var parts = s.Split(' ');
double result = double.Parse(parts[1]);
switch(parts[0])
{
case "Spr":
result += .25;
break;
case "Sum"
result += .5;
break;
case "Fall":
result += .75;
break;
}
return result;
});
I also considered Array.Sort, which might be a little faster, but you also mentioned that sometimes these are ArrayLists.
精彩评论