I am trying to sort a string-number column, e.g. N1, N10, N100, N2 and I am expecting the results N1, N2, N10, N100 but the sorting doesn't work, I am getting the same values N1, N10, N100, N2 in the same order.
I wrote the following code.
static class ExtensionMethod
{
public static DataTable SortAlphaNumeric(this DataTable datatable, string columnName)
{
return datatable.AsEnumerable()
.OrderBy(r => r.Field<String>(columnName), new CustomComparer())
.CopyToDataTable();
}
}
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var numberX = Regex.Match(x, @"\d+").Value;
var numberY = Regex.Match(y, @"\d+").Value;
var alphaX = Regex.Match(x, @"[^a-z]").Value;
var alphaY = Regex.Match(y, @"[^a-z]").Value;
if (alphaX.CompareTo(alphaY) == 0)
return numberX.CompareTo(numberY);
else if (alphaX.CompareTo(alphaY) < 0)
return -1;
return 1;
}
}
// Code example
class TestExample
{
public void Test()
{
var dt = new DataTable();
dt.Columns.Add("AlphaNumeric", Type.GetType("System.String"));
var row = dt.NewRow();
row["AlphaNumeric"] = "N1";
dt.Rows.Add(row);
row = dt.NewRow();
row["AlphaNumeric"] = "N10";
dt.Rows.Add(row);
row = dt.NewRow();
row["AlphaNumeric"] = "N100";
dt.Rows.Add(row);
row = dt.NewRow();
row["AlphaNumeric"] = "N2";
dt.Rows.Add(row);
var orderedDt = dt.SortAlphaNumeric("AlphaNumeric");
}
}
Change in your Comparer: