LINQ to datasets require the use of System.Core.dll, System.Data.dll and System.Data.DataSetExtensions.dll, add references System.Data and System.Data.DataSetExtensions to the project.
1. DataTable Read List
DataSet ds = new DataSet ();//Omit the DS's fill code datatable products = ds. tables["Product"];ienumerable<datarow> rows = from P in products. AsEnumerable () Select P;foreach (DataRow row in rows) { Console.WriteLine (row. Field<string> ("ProductName"));}
DataSet ds = new DataSet ();//Omit the DS's fill code 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);}
var products = ds. tables["Product"]. AsEnumerable (); var query = from P in the products Select p.field<string> ("ProductName");
2. DataTable Query
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 ") });
3. DataTable Data Sorting
var rows = products. AsEnumerable () . Where (P = = p.field<decimal> ("UnitPrice") > 10m) . (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 products. AsEnumerable () p.field<int> ("SortOrder") select p;ienumerable<datarow> rows = Expr. ToArray (); foreach (var row in rows) { Console.WriteLine (row). Field<string> ("ProductName"));}
var expr = from P in DS. tables["Product"]. AsEnumerable () p.field<int> ("SortOrder"), p.field<string> ("ProductName") descending Select P;
4. Multiple DataTable queries
var query = from P in DS. tables["Product"]. AsEnumerable () from the 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") };
5. DataTable Grouping
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"));} }
Query the number of each CategoryID in product:
var expr = from P in DS. tables["Product"]. AsEnumerable () group P by p.field<int> ("CategoryID") into G Select New { CategoryID = G.key, Productscount = G.count () };
C # LINQ series: DataTable Operations for LINQ to Datasets and Conversion of DataTable and LINQ to each other