C# DataTable用法示例详解,将会对C# DataTable select,sort排序,Linq过滤等常用方法进行简单的讲解
先来看看DataTable Select方法有哪几种,如下表所示:NameDescription
Select()Gets an array of all DataRow objects. #查找所有数据,返回DataRow数组(以下全部返回数组)
Select(String)Gets an array of all DataRow objects that match the filter criteria. #根据匹配条件查找
Select(String, String)Gets an array of all DataRow objects that match the filter criteria, in the specified sort order.
#根据匹配条件查找,并排序(第二个参数是排序规则)
Select(String, String, DataViewRowState)Gets an array of all DataRow objects that match the filter in the order of the sort that match the specified state.
下面是一个C# DataTable用法示例,讲述了使用Select(Select(String, String)的第二个参数是排序规则)和Linq表达式来过滤数据,下面的两个用法请分开来学习。namespace demo
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(Int32));
table.Columns.Add("NAME", typeof(string));
table.Columns.Add("AGE", typeof(Int32));
for (int i=1; i<=10; i++)
{
DataRow newRow = table.NewRow();
newRow["ID"] = i;
newRow["NAME"] = "张三"+i;
newRow["AGE"] = i+5;
table.Rows.Add(newRow);
}
//排序 :id大于等于5,并按age年龄倒序
string expression = "ID >= 5";
string sortAge = "AGE DESC";
DataRow[] foundRows = table.Select(expression, sortAge);
for (int i = 0; i
{
//查看age年龄字段是否排序ok
Console.WriteLine(foundRows[i][2]);
}
Console.Read();
//Linq过滤操作
var ros = table.AsEnumerable().Where(e => e.Field("Age") >= 10);
DataTable filterTable = ros.Count() <= 0 ? null : ros.CopyToDataTable();
foreach (DataRow row in filterTable.Rows)
{
//输出age年龄大于10岁
Console.WriteLine(row[2]);
}
Console.Read();
}
}
}
来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/kuozhan/567.html