LINQ to DataSet詳細概括
學習LINQ時,經常會遇到LINQ to DataSet問題,這里將介紹LINQ to DataSet問題的解決方法。
使用 LINQ to DataSet 可以更快更容易地查詢在 DataSet 對象中緩存的數據。具體而言,通過使開發人員能夠使用編程語言本身而不是通過使用單獨的查詢語言來編寫查詢,LINQ to DataSet 可以簡化查詢。對于現在可以在其查詢中利用 Visual Studio 所提供的編譯時語法檢查、靜態類型和 IntelliSense 支持的 Visual Studio 開發人員,這特別有用。
LINQ to DataSet 也可用于查詢從一個或多個數據源合并的數據。這可以使許多需要靈活表示和處理數據的方案(例如查詢本地聚合的數據和 Web 應用程序中的中間層緩存)能夠實現。具體地說,一般報告、分析和業務智能應用程序將需要這種操作方法。
LINQ to DataSet 功能主要通過 DataRowExtensions 和 DataTableExtensions 類中的擴展方法公開。LINQ to DataSet 基于并使用現有的 ADO.NET 2.0 體系結構生成,在應用程序代碼中不能替換 ADO.NET 2.0。現有的 ADO.NET 2.0 代碼將繼續在 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("");
- }
【編輯推薦】