我们经常遇到这样的问题,字符串尾部带数字,如何正确排序;
首先设置GridView ,Columns 的相关列,设置属性中,SortMode为Custom
解决思路,把字符串尾缀数字,分离出来。先比较去除尾部数字的字符串,再比较尾部数字位。
gridView.CustomColumnSort += GridView_CustomColumnSort;
private void GridView_CustomColumnSort(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnSortEventArgs e)
{
if (e.Column == gridColumn)
{
string value1 = e.Value1.ToString();
string value2 = e.Value2.ToString();
var cc1 = GetNumberIndex(value1);
var cc2 = GetNumberIndex(value2);
if (cc1 > -1 && cc2 > -1)
{
string zm1 = value1.Substring(0, cc1);
string zm2 = value2.Substring(0, cc2);
if (zm1 == zm2)
{
string nb1 = value1.Substring(cc1);
string nb2 = value2.Substring(cc2);
decimal.TryParse(nb1, out decimal dec1);
decimal.TryParse(nb2, out decimal dec2);
int result = Comparer<decimal>.Default.Compare
(dec1, dec2);
e.Result = result;
e.Handled = true;
}
}
}
}
private int GetNumberIndex(string value)
{
int v = -1;
if (value != null && value.Length > 1)
{
int i = 0;
for (; i < value.Length; i++)
{
if (char.IsNumber(value[i]))
{
if (i != 0)
{
v = i;
}
break;
}
}
}
return v;
}