LINQ to DataSet 中的查詢
其中範例中,大致分成兩種,一為查詢運算式語法,二為以方法為基礎的查詢語法
其實對我而言,就是一個有from,另一個沒有~
當我遇到要做Order By時,似乎只有看到有from那種語法有範例。
查詢運算式語法
DataTable products = ds.Tables["Product"]; IEnumerable<datarow> query = from product in products.AsEnumerable() select product; Console.WriteLine("Product Names:"); foreach (DataRow p in query) { Console.WriteLine(p.Field<string>("Name")); }
DataTable products = ds.Tables["Product"]; IEnumerable<datarow> query = from product in products.AsEnumerable() orderby product.Field<decimal>("ListPrice") descending select product; // Force immediate execution of the query. IEnumerable<datarow> productsArray = query.ToArray(); Console.WriteLine("Every price from highest to lowest:"); foreach (DataRow prod in productsArray) { Console.WriteLine(prod.Field<decimal>("ListPrice")); }
以方法為基礎的查詢語法
DataTable products = ds.Tables["Product"]; var query = products.AsEnumerable(). Select(product => new { ProductName = product.Field<string>("Name"), ProductNumber = product.Field<string>("ProductNumber"), Price = product.Field<decimal>("ListPrice") }); Console.WriteLine("Product Info:"); foreach (var productInfo in query) { Console.WriteLine("Product name: {0} Product number: {1} List price: ${2} ", productInfo.ProductName, productInfo.ProductNumber, productInfo.Price); }
It is better to use the first one.
回覆刪除