SQL之datatable中的数据进行操作(Westcon借测协议报表)
通过SQL语句查出来,以ls.id升序排列,number降序排列,并放在datatable里
string sql = string.Empty; sql = string.Format(@"SELECT ls.id, CONVERT(varchar(10),ls.create_time,120) AS create_time,ls.TotalStatusSchema, SUBSTRING ( ISNULL(ls.number,'9999999999') , 7 , 99 ) as Sort,ISNULL(ls.number,'待定') as number, ISNULL( a.AreaName,'未知')AS AreaName,[dbo].[aspnet_x_GetUserProfileProperty]('/',ls.create_user,'NameEn')as create_user, ls.company_name, ls.user_company_name,ls.rent_name,d.devicename,d.devicemodel,d.devicesn,CONVERT(varchar(10),ls.startdate,120) AS start_date, CONVERT(varchar(10),ls.end_date,120) AS end_date,CONVERT(varchar(10),ls.return_date,120) AS return_date, DATEDIFF(DAY,getdate(),ls.end_date) AS countDay ,ls.statue,ls.contact_name, ls.contact_mobile,ls.contact_mail,ls.logistics_number ,case when charindex('纸质协议',ls.files_status) > 0 then '纸质协议' Else '' end pod ,case when charindex('送货单',ls.files_status) > 0 then '送货单' Else '' end txt FROM v_Lease ls INNER JOIN v_Device d ON d.rent_id=ls.id LEFT OUTER JOIN v_Area a ON a.NAME=ls.create_user where ls.TotalStatusSchema<>'draft' {0} order by ls.id asc,number desc ", FilterConditions); string content = ""; DataTable dt = access.ExecuteTable(sql);
声明一个泛型数组,对dt的数据进行循环和判断操作
List<string> arr = new List<string>(); for (int i = 0; i < dt.Rows.Count; i++) {
//判断TotalStatueShchema=='Work' ,排除第一个条件 if (dt.Rows[i]["TotalStatusSchema"].ToString()== "Work") { dt.Rows[i]["statue"] = "取消"; } else {
//判断id是否有包含的, if (arr.Contains(dt.Rows[i]["id"].ToString())) {
//如果有就取第一条 dt.Rows[i]["statue"] = "续签"; } else {
//其他的根据条件做相应的操作 if (dt.Rows[i]["TotalStatusSchema"].ToString() == "done") { dt.Rows[i]["statue"] = "还回"; } else if (dt.Rows[i]["TotalStatusSchema"].ToString() == "WorkflowAbort") { dt.Rows[i]["statue"] = "取消"; } else { dt.Rows[i]["statue"] = "测试中"; } arr.Add(dt.Rows[i]["id"].ToString()); } } }
新建一个datatable,将Sort这个列转换成int类型,进行升序排列,最后将数据插入到dt中
DataTable dtnew = dt.Clone(); dtnew.Columns["Sort"].DataType = typeof(int); foreach (DataRow s in dt.Rows) { dtnew.ImportRow(s); } dt.DefaultView.Sort = "Sort ASC"; dt = dt.DefaultView.ToTable();