DataTable排序
文章目录
前言
在使用DataTable进行数据存储的时候,往往遇到需要对表中数据进行排序的需求,这里给大家提供一种排序的方式,话不多说直接上代码。
代码如下(示例):
//add by zxm
DataTable dtcopy = new DataTable();
dtcopy = dt.Copy();
//增加用于排序的列 add by zxm
dtcopy.Columns.Add("RateSort", typeof(double));
//排序 add by zxm 截取编号中的数字作为排序的依据
for (int i = 0; i < dtcopy.Rows.Count; i++)
{
//从下标2的位置开始截取对应长度的数字作为排序数字
string str1 = dtcopy.Rows[i]["deviceid"].ToString();
string[] mstrarr = str1.Split('#');
string number = "";
if (mstrarr[0].Length == 4)
{
number = mstrarr[0].Substring(2,1);
}
else if(mstrarr[0].Length == 5)
{
number = mstrarr[0].Substring(2, 2);
}
else if(mstrarr[0].Length == 6)
{
number = mstrarr[0].Substring(2, 3);
}
else if(mstrarr[0].Length == 7)
{
number = mstrarr[0].Substring(2, 4);
}
double douRate = double.Parse(number);
//将数字存到表的排序的那一列
dtcopy.Rows[i]["RateSort"] = douRate;
}
//排序
DataView dv = dtcopy.DefaultView;
dv.Sort = "RateSort ASC";
dt = dtcopy.DefaultView.ToTable();//返回一个新的DataTable