This works the way you have described. It may not be very efficient so you may want to optimise it somewhat:
public static int Compare(string first, string second)
{
if (object.ReferenceEquals(first, second))
return 0;
if (object.ReferenceEquals(null, first)) // second cannot be null
return -1;
// neither string can be null
char\[\] digits = new char\[\] { '0', '1', '2', '3', '4', '5', '6', '7', '8','9' };
int firstDigitIndex = first.IndexOfAny(digits);
int secondDigitIndex = second.IndexOfAny(digits);
string firstLhs = firstDigitIndex == -1 ? first : first.Substring(0, firstDigitIndex);
string secondLhs = secondDigitIndex == -1 ? second : second.Substring(0, firstDigitIndex);
int result = firstLhs.CompareTo(secondLhs);
if (result == 0)
{
// left hand sides are equal so sort on numeric part
int firstInteger = 0;
int secondInteger = 0;
if (firstDigitIndex > -1)
int.TryParse(first.Substring(firstDigitIndex), out firstInteger);
if (secondDigitIndex > -1)
int.TryParse(second.Substring(secondDigitIndex), out secondInteger);
result = firstInteger.CompareTo(secondInteger);
}
return result;
}
Test:
SortAndWriteList(new List(new string\[\] { "ABC 1", "ABC 10", "ABC 2", "ABC 100" }));
Console.WriteLine();
SortAndWriteList(new List(new string\[\] { "ADBCDEF - 1", "ADBCDEF - 10", "ADBCDEF - 3" }));
Console.WriteLine();
Console.ReadKey();
private static void SortAndWriteList(List list)
{
if (list != null)
{
list.Sort(new Comparison(Compare));
foreach (string item in list)
Console.WriteLine(item);
}
}
Result:
ABC 1
ABC 2
ABC 10
ABC 100
ADBCDEF - 1
ADBCDEF - 3
ADBCDEF - 10
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (