Sometimes IComparer falls short when on has a need to sort on different, for lack of a better term, data columns. Before writing an IComparer interface for sort, try using Linq’s Orderby.
In the forums the user had data, in string lines, which looked like this
3 months ending 9/30/2007
9 months ending 9/30/2007
3 months ending 9/30/2008
9 months ending 9/30/2008
The user needed the white items sorted first in ascending fashion and the red year items sorted descending. Because the data was all in a string and needed differing sorts, je was having problems with sort with a custom IComparer class.
I recommend that he use regex to parse out the items then use linq to sort. Here is the result. Note I merged all data into one string where each line is a true line.
string input =
@"3 months ending 9/30/2007
9 months ending 9/30/2007
3 months ending 9/30/2008
9 months ending 9/30/2008";
string pattern = @"(?<Total>\d\d?)(?:[^\d]+)(?<Date>[\d/]+)";
var items =
from Match m in Regex.Matches( input, pattern )
select new
{
Total = m.Groups["Total"].Value,
Date = DateTime.Parse( m.Groups["Date"].Value ),
Full = m.Groups[0].Value
};
var values = from p in items
orderby p.Total, p.Date.Year descending
select p;
foreach ( var itm in values )
Console.WriteLine( itm.Full );
/* Outputs
3 months ending 9/30/2008
3 months ending 9/30/2007
9 months ending 9/30/2008
9 months ending 9/30/2007
*/
#1 by Eric Duncan on August 3, 2010 - 5:25 pm
Quote
Can’t see any code in IE8 or FF35. JS error in IE8.
#2 by OmegaMan on August 3, 2010 - 5:45 pm
Quote
Let me test the blog…..done try it now! Thanks for telling me!