C# 在datatable中添加自定义字段
DataTable dt = new DataTable(); sql.Append(" SELECT a from b "); dt = SqlHelper.GetDataTable(sql.ToString());
sql = new StringBuilder(); sql.Append(" SELECT c from d "); var jcdt = SqlHelper.GetDataTable(sql.ToString()); //重要 DataColumn dataColumn1 = new DataColumn("自定义字段名称", typeof(Int32)); DataColumn dataColumn2 = new DataColumn("自定义字段名称", typeof(Int32)); dt.Columns.Add(dataColumn1); dt.Columns.Add(dataColumn2); //给新增的字段赋值 foreach (DataRow item in dt.Rows)//item:行 相当于dr {
//根据某个字段查询数据 item:行 [0]:表示列 DataRow[] num = jcdt.Select("ID=" + item[0]); item[5] = num.Count();//赋值 int i = num.Count(); DataRow[] hg = jcdt.Select("ID=" + item[0] + "and VerID=1");//查询条件 item[6] = hg.Count();//赋值 item[7] = num.Count() - hg.Count();//赋值
//用三目运算判断值再赋值 item[8] = num.Count() > 0 ? (Convert.ToDecimal(hg.Count()) / Convert.ToDecimal(num.Count()) * 100).ToString("f2") + "%" : "0.00%"; } return format.ResultJsonData("SUCCESS", "获取信息成功!", dt);