LINQ to DataSet需要使用System.Core.dll、System.Data.dll和System.Data.DataSetExtensions.dll,在项目中添加引用System.Data和System.Data.DataSetExtensions。
1. DataTable读取列表
DataSet ds = new DataSet();// 省略ds的Fill代码DataTable products = ds.Tables["Product"];IEnumerablerows = from p in products.AsEnumerable() select p;foreach (DataRow row in rows){ Console.WriteLine(row.Field ("ProductName"));}
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);}
var products = ds.Tables["Product"].AsEnumerable();var query = from p in products select p.Field("ProductName");
2. DataTable查询
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数据排序
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") });
var expr = from p in products.AsEnumerable() orderby p.Field ("SortOrder") select p;IEnumerablerows = expr.ToArray();foreach (var row in rows){ Console.WriteLine(row.Field ("ProductName"));}
var expr = from p in ds.Tables["Product"].AsEnumerable() orderby p.Field ("SortOrder"), p.Field("ProductName") descending select p;
4. 多个DataTable查询
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") };
5. DataTable分组
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的数目:
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() };