I am trying to sort an array of tab-delimited strings. I call the split function on tab characters on each element to break the strings into string arrays. I then do a comparison on the date element to return the order that they should be in. If the dates are equal I do a secondary comparison on a string field. My implementation of the IComparer interface looks like this:
class CompareLines : IComparer<string>
{
public int Compare(string x, string y)
{
string[] bSplitX = x.Split('\t');
string[] bSplitY = y.Split('\t');
int bYearX = Int32.Parse(bSplitX[4].Substring(4, 4));
int bMonthX = Int32.Parse(bSplitX[4].Substring(0, 2));
int bDayX = Int32.Parse(bSplitX[4].Substring(2, 2));
int bYearY = Int32.Parse(bSplitY[4].Substring(4, 4));
int bMonthY = Int32.Parse(bSplitY[4].Substring(0, 2));
int bDayY = Int32.Parse(bSplitY[4].Substring(2, 2));
DateTime bTempDateX = new DateTime(bYearX, bMonthX, bDayX);
DateTime bTempDateY = new DateTime(bYearY, bMonthY, bDayY);
if (DateTime.Compare(bTempDateX, bTempDateY) > 0)
{
return 1;
}
else if (DateTime.Compare(bTempDateX, bTempDateY) < 0)
{
return -1;
}
else if (DateTime.Compare(bTempDateX, bTempDateY) == 0)
{
if (String.Compare(bSplitX[3], bSplitY[3]) > 0)
{
return 1;
}
else
{
return -1;
}
}
else
{
Console.WriteLine("ahhh wtf"); //should never be reached. This message has never appeared in my console.
return 0;
}
}
}
My problem is that it will work sometimes and not others. Does anyone have any reasons why the above code would not work 100% of the time?
This has been hurting my brain for a couple days now and I really do not understand why it is not working.
DateTime.ParseExact? And how do you expect us to help you without any information about the input, expected output, or what happens when it goes wrong?