Linq操作Datable

来源:互联网 发布:淘宝客服那那里应聘 编辑:程序博客网 时间:2024/06/08 20:17

一、Datable简单查询

 
DataSet ds = new DataSet();// 省略ds的Fill代码DataTable products = ds.Tables["Product"];var rows = products.AsEnumerable()    .Select(p => new    {        ProductID = p.Field<int>("ProductID"),        ProductName = p.Field<string>("ProductName"),        UnitPrice = p.Field<decimal>("UnitPrice")    });foreach (var row in rows){    Console.WriteLine(row.ProductName);} 

二、Datable代where过滤条件的查询

var rows = products.AsEnumerable()    .Where(p => p.Field<decimal>("UnitPrice") > 10m)    .Select(p => new    {        ProductID = p.Field<int>("ProductID"),        ProductName = p.Field<string>("ProductName"),        UnitPrice = p.Field<decimal>("UnitPrice")    });

三、DataTable数据排序

var rows = products.AsEnumerable()    .Where(p => p.Field<decimal>("UnitPrice") > 10m)    .OrderBy(p => p.Field<int>("SortOrder"))    .Select(p => new    {        ProductID = p.Field<int>("ProductID"),        ProductName = p.Field<string>("ProductName"),        UnitPrice = p.Field<decimal>("UnitPrice")    });

var expr = from p in ds.Tables["Product"].AsEnumerable()           orderby p.Field<int>("SortOrder"), p.Field<string>("ProductName") descending           select p;

四、多个DataTable查询

var query = from p in ds.Tables["Product"].AsEnumerable()            from c in ds.Tables["Category"].AsEnumerable()            where p.Field<int>("CategoryID") == c.Field<int>("CategoryID")                && p.Field<decimal>("UnitPrice") > 10m            select new            {                ProductID = p.Field<int>("ProductID"),                ProductName = p.Field<string>("ProductName"),                CategoryName = c.Field<string>("CategoryName")            };

五、DataTable分组

 

var query = from p in ds.Tables["Product"].AsEnumerable()            group p by p.Field<int>("CategoryID") into g            select new            {                CategoryID = g.Key,                Products = g            };foreach (var item in query){    Console.WriteLine(item.CategoryID);    foreach (var p in item.Products)    {        Console.WriteLine(p.Field<string>("ProductName"));    }}

原创粉丝点击