LINQ to DataSet詳細概括
學習LINQ時,經(jīng)常會遇到LINQ to DataSet問題,這里將介紹LINQ to DataSet問題的解決方法。
使用 LINQ to DataSet 可以更快更容易地查詢在 DataSet 對象中緩存的數(shù)據(jù)。具體而言,通過使開發(fā)人員能夠使用編程語言本身而不是通過使用單獨的查詢語言來編寫查詢,LINQ to DataSet 可以簡化查詢。對于現(xiàn)在可以在其查詢中利用 Visual Studio 所提供的編譯時語法檢查、靜態(tài)類型和 IntelliSense 支持的 Visual Studio 開發(fā)人員,這特別有用。
LINQ to DataSet 也可用于查詢從一個或多個數(shù)據(jù)源合并的數(shù)據(jù)。這可以使許多需要靈活表示和處理數(shù)據(jù)的方案(例如查詢本地聚合的數(shù)據(jù)和 Web 應用程序中的中間層緩存)能夠?qū)崿F(xiàn)。具體地說,一般報告、分析和業(yè)務(wù)智能應用程序?qū)⑿枰@種操作方法。
LINQ to DataSet 功能主要通過 DataRowExtensions 和 DataTableExtensions 類中的擴展方法公開。LINQ to DataSet 基于并使用現(xiàn)有的 ADO.NET 2.0 體系結(jié)構(gòu)生成,在應用程序代碼中不能替換 ADO.NET 2.0。現(xiàn)有的 ADO.NET 2.0 代碼將繼續(xù)在 LINQ to DataSet 應用程序中有效。
下面看一個例子:
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture
- FillDataSet(ds);
- DataTable products = ds.Tables["Product"];
- var query =
- from product in products.AsEnumerable()
- where !product.IsNull("Color") &&
- (string)product["Color"] == "Red"
- select new
- {
- Name = product["Name"],
- ProductNumber = product["ProductNumber"],
- ListPrice = product["ListPrice"]
- };
- foreach (var product in query)
- {
- Console.WriteLine("Name: {0}", product.Name);
- Console.WriteLine("Product number: {0}", product.ProductNumber);
- Console.WriteLine("List price: ${0}", product.ListPrice);
- Console.WriteLine("");
- }
使用擴展之后的例子:
- // Fill the DataSet.
- DataSet ds = new DataSet();
- ds.Locale = CultureInfo.InvariantCulture;
- FillDataSet(ds);
- DataTable products = ds.Tables["Product"];
- var query =
- from product in products.AsEnumerable()
- where product.Field<string>("Color") == "Red"
- select new
- {
- Name = product.Field<string>("Name"),
- ProductNumber = product.Field<string>("ProductNumber"),
- ListPrice = product.Field("ListPrice")
- };
- foreach (var product in query)
- {
- Console.WriteLine("Name: {0}", product.Name);
- Console.WriteLine("Product number: {0}", product.ProductNumber);
- Console.WriteLine("List price: ${0}", product.ListPrice);
- Console.WriteLine("");
- }
【編輯推薦】


















