一 复制DataTable中符合条件的DataRow到新的DataTable中
One:
DataTable TableTemp = new DataTable();//临时table
DataTable tableAd =newWeb.DAL.FreeBase().TranSQLGetTable("select a.ClassName,b.ParentId,b.Name,b.Pic,b.Url,b.Sorts from AdClass a inner join Ad b on a.Id=b.ParentId");//查询的结果if(tableAd !=null&& tableAd.Rows.Count >0)
{Tableflag=tableAd.Copy();//复制结构
Tableflag.Clear();//清除临时数据foreach(DataRow drintableAd.Rows)
{if(dr["ParentId"].ToString().Equals("17"))
{
DataRow temPRow=TableTemp.NewRow(); //创建与该表相同架构的新行
tempRow["ClassName"] = dr["ClassName"];
tempRow["ParentId"] = dr["ParentId"];
tempRow["Name"] = dr["Name"];
tempRow["Pic"] = dr["Pic"];
tempRow["Url"] = dr["Url"];
tempRow["Sorts"] = dr["Sorts"];
TableTemp.Rows.Add(tempRow);
}
}
}
Two:
#regionDataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回///<summary>///DataTable筛选,排序返回符合条件行组成的新DataTable或直接用DefaultView按条件返回///eg:SortExprDataTable(dt,"Sex='男'","Time Desc",1)///</summary>///<param name="dt">传入的DataTable</param>///<param name="strExpr">筛选条件</param>///<param name="strSort">排序条件</param>///<param name="mode">1,直接用DefaultView按条件返回,效率较高;2,DataTable筛选,排序返回符合条件行组成的新DataTable</param>publicstaticDataTable SortDataTable(DataTable dt,stringstrExpr,stringstrSort,intmode)
{switch(mode)
{case1://方法一直接用DefaultView按条件返回dt.DefaultView.RowFilter =strExpr;
dt.DefaultView.Sort=strSort;returndt;case2://方法二DataTable筛选,排序返回符合条件行组成的新DataTableDataTable dt1 =newDataTable();
DataRow[] GetRows=dt.Select(strExpr, strSort);//复制DataTable dt结构不包含数据dt1 =dt.Clone();foreach(DataRow rowinGetRows)
{
dt1.Rows.Add(row.ItemArray);
}returndt1;default:returndt;
}
}#endregion
View Code
//选取ParentId=17的所以行,并根据Sorts降序排序
TableTemp = SortDataTable(tableAd,"ParentId=17","Sorts Desc",2);
Three:
#region获取DataTable前几条数据///<summary>///获取DataTable前几条数据///</summary>///<param name="TopItem">前N条数据</param>///<param name="oDT">源DataTable</param>///<returns></returns>publicstaticDataTable DtSelectTop(intTopItem, DataTable oDT)
{if(oDT.Rows.Count < TopItem)returnoDT;
DataTable NewTable=oDT.Clone();
DataRow[] rows= oDT.Select("1=1");for(inti =0; i < TopItem; i++)
{
NewTable.ImportRow((DataRow)rows[i]);
}returnNewTable;
}#endregion
View Code
//选取前7行数据
TableTemp = DtSelectTop(7, Table1);