datatable linq查询

您所在的位置:网站首页 获取datatable的行数 datatable linq查询

datatable linq查询

2024-06-18 03:54| 来源: 网络整理| 查看: 265

DataTable通过调用AsEnumerable()方法,从而运用Linq查询。其中AsEnumerable方法在System.Data.DataSetExtensions.dll中定义,一般VS会自动引用这个dll。

一、datatable linq查询实例

1. DataTable读取列表

  C# 代码    复制 DataSet ds = new DataSet(); // 省略ds的Fill代码 DataTable products = ds.Tables["Product"]; IEnumerable rows = from p in products.AsEnumerable() select p; foreach (DataRow row in rows) { Console.WriteLine(row.Field("ProductName")); }   C# 代码    复制 DataSet ds = new DataSet(); // 省略ds的Fill代码 DataTable products = ds.Tables["Product"]; var rows = products.AsEnumerable() .Select(p => new { ProductID = p.Field("ProductID"), ProductName = p.Field("ProductName"), UnitPrice = p.Field("UnitPrice") }); foreach (var row in rows) { Console.WriteLine(row.ProductName); }

2. DataTable linq where 查询

  C# 代码    复制 var rows = products.AsEnumerable() .Where(p => p.Field("UnitPrice") > 10m) .Select(p => new { ProductID = p.Field("ProductID"), ProductName = p.Field("ProductName"), UnitPrice = p.Field("UnitPrice") });

3、DataTable linq 数据排序

  C# 代码    复制 var rows = products.AsEnumerable() .Where(p => p.Field("UnitPrice") > 10m) .OrderBy(p => p.Field("SortOrder")) .Select(p => new { ProductID = p.Field("ProductID"), ProductName = p.Field("ProductName"), UnitPrice = p.Field("UnitPrice") });   C# 代码    复制 var expr = from p in products.AsEnumerable() orderby p.Field("SortOrder") select p; IEnumerable rows = expr.ToArray(); foreach (var row in rows) { Console.WriteLine(row.Field("ProductName")); }   C# 代码    复制 var expr = from p in ds.Tables["Product"].AsEnumerable() orderby p.Field("SortOrder"), p.Field("ProductName") descending select p;

4、DataTable分组 

C# 代码    复制 var query = from p in ds.Tables["Product"].AsEnumerable() group p by p.Field("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("ProductName")); } }

查询Product中每个CategoryID的数目

  C# 代码    复制 var expr = from p in ds.Tables["Product"].AsEnumerable() group p by p.Field("CategoryID") into g select new { CategoryID = g.Key, ProductsCount = g.Count() };

5、多个DataTable查询

  C# 代码    复制 var query = from p in ds.Tables["Product"].AsEnumerable() from c in ds.Tables["Category"].AsEnumerable() where p.Field("CategoryID") == c.Field("CategoryID") && p.Field("UnitPrice") > 10m select new { ProductID = p.Field("ProductID"), ProductName = p.Field("ProductName"), CategoryName = c.Field("CategoryName") };

二、linq 对象转换为DataTable

通过CopyToDataTable()方法

  C# 代码    复制 DataTable newD1t = query1.CopyToDataTable(); foreach (DataRow item in newD1t.Rows) { System.Console.WriteLine(item["Name"]); }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3