我正在尝试对字符串数列进行排序,例如N1,N10,N100,N2,我期望结果为N1,N2,N10,N100,但排序不起作用,我以相同的顺序获得了相同的值N1,N10,N100,N2.
我写了下面的代码.
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");
}
}
解决方法:
在您的比较器中进行更改:
var numberX = int.Parse(Regex.Match(x, @"\d+").Value);
var numberY = int.Parse(Regex.Match(y, @"\d+").Value);