C#中DataTable实现筛选备忘
说明:
DataTable进行过滤筛选,常用的一些方法为:Select,dataview
1. 直接循环遍历获取
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["C1"].ToString() == "abc")
{
}
}
2. 使用LinQ
DataTable dt = new DataTable();
DataRow[] drArr = dt.Select(" C1=’abc’ ");
DataRow[] drArr = dt.Select("C1 LIKE ’abc%’");
DataRow[] drArr = dt.Select("’abc’ LIKE C1 + ’%’", "C2 DESC");
DataRow[] drArr = dt.Select("C1=’abc’", "C2 DESC");
DataTable dtNew = dt.Clone();
for (int i = 0; i < drArr.Length; i++)
{
dtNew.ImportRow(drArr[i]);
}
3. 利用DataView的RowFilter 实现筛选
DataTable dataSource = new DataTable();
DataView dv = dataSource.DefaultView;
dv.RowFilter = "columnA = 'abc'";
DataTable newTable1 = dv.ToTable();
DataTable newTable2 = dv.ToTable("NewTableName");
DataTable newTable3 =
dv.ToTable(true, new string[] { "columnA,columnF,columnC" });
DataTable newTable4 =
dv.ToTable("NewTableName", true, new string[] { "columnA,columnF,columnC" });