DataTable常用代码

构建DataTable

DataTable dtUserInfo = new DataTable("UserInfo");//1.构建DataTable
dtUserInfo.Columns.Add("UserName", typeof(string));//2.为DataTable设置列
//dtUserInfo.Columns.Add("UserName");
dtUserInfo.Columns.Add("Gender", typeof(int));DataRow drInpuUserInfo = dtUserInfo.NewRow();//3.从获取一个DataRow对象
drInpuUserInfo["UserName"] = dt.Rows[0]["UserName"];//4.为这个DataRow对象赋值,赋值方式一
dtUserInfo.Rows.Add(drInpuUserInfo);//5.将赋值好的dr加回dt

dt.Rows.Add("1", "xxx", "yyy", 1);//dr赋值方式二    


DataTable.ImportRow(dr)与DataTable.Rows.Add(dr)区别

DataRow dr = dtResult.NewRow();
//...
dtResult.Rows.Add(dr.ItemArray);
DataTable sourceDt = this.GetSqlData(sql, parms);
DataTable destincDt = sourceDt.Clone();//仅复制结构
//....
destincDt.ImportRow(sourceDt.Rows[i]);//用来将其他表的DataRow复制到当前的表,如果是复制自己的DataRow毫无意义,是不会成功的。
//destincDt.Rows.Add(sourceDt.Rows[i]);is Wrong

DataRow转换为DataTable工具方法

public DataTable SreeenDataTable(DataTable dt, string strWhere)
{
    if (dt.Rows.Count <= 0) return dt;        //当数据为空时返回
    DataTable dtNew = dt.Clone();         //复制数据源的表结构
    DataRow[] dr = dt.Select(strWhere);  //strWhere条件筛选出需要的数据!
    for (int i = 0; i < dr.Length; i++)
    {
        dtNew.Rows.Add(dr[i].ItemArray);  // 将DataRow添加到DataTable中
    }
    return dtNew;
}

Select Compute

dt.Select("QuestionID=" + QuestionID + " And RelationID=30");
dt.Compute("Sum(Num)", "")

 DataTable添加列

DataTable dt_1 = iniResultDs.Tables[0]; //组装扩展字段
DataTable dt_2 = iniResultDs.Tables[1];  //扩展字段
for (int i = 0; i < dt_2.Rows.Count; i++)
{
  string columnName = dt_2.Rows[i]["ColumnName"].ToString();
  string columnValue = dt_2.Rows[i]["Value"].ToString();
  dt_1.Columns.Add(columnName);
  dt_1.Rows[0][columnName] = columnValue;
}
DataSet resultDs = new DataSet();
resultDs.Tables.Add(dt_1.Copy());

 DataTable取列

 

DataTable dataTable = talentBLL.GetPuzzleBasicPageDt(parms, "LastUpdateTime DESC,CreatedTime DESC,BasicID DESC", length, page, out recordCount);
dataTable = dataTable.DefaultView.ToTable(false, new string[] { "BasicID", "Name", "Gender", "City","Phone", "Email", "SalaryFromTo",
"SalaryLow","SalaryHigh","WorkYear","CompanyName","Positions"});

 

DataTable--可能你不知道的一些功能(排序、查询、合并操作)

C#自带计时器(用于简单的性能估算)

var text = "Whilst playing badminton, I ruptured my Achilles tendon."; //GetTestText();//生成测试文本
Console.WriteLine(text);
IStringAna ana = new StringAna();
var sp = Stopwatch.StartNew();
var rlt = ana.Ana(text);//需测算的句子拆分单词
Console.WriteLine($"Elapsed:{sp.ElapsedTicks}");//简便的性能测试方法,计时器

 

posted @ 2016-12-06 09:03  轴轴  阅读(558)  评论(0编辑  收藏  举报