LINQ to DataSet詳細(xì)概括
學(xué)習(xí)LINQ時(shí),經(jīng)常會(huì)遇到LINQ to DataSet問(wèn)題,這里將介紹LINQ to DataSet問(wèn)題的解決方法。
使用 LINQ to DataSet 可以更快更容易地查詢(xún)?cè)?DataSet 對(duì)象中緩存的數(shù)據(jù)。具體而言,通過(guò)使開(kāi)發(fā)人員能夠使用編程語(yǔ)言本身而不是通過(guò)使用單獨(dú)的查詢(xún)語(yǔ)言來(lái)編寫(xiě)查詢(xún),LINQ to DataSet 可以簡(jiǎn)化查詢(xún)。對(duì)于現(xiàn)在可以在其查詢(xún)中利用 Visual Studio 所提供的編譯時(shí)語(yǔ)法檢查、靜態(tài)類(lèi)型和 IntelliSense 支持的 Visual Studio 開(kāi)發(fā)人員,這特別有用。
LINQ to DataSet 也可用于查詢(xún)從一個(gè)或多個(gè)數(shù)據(jù)源合并的數(shù)據(jù)。這可以使許多需要靈活表示和處理數(shù)據(jù)的方案(例如查詢(xún)本地聚合的數(shù)據(jù)和 Web 應(yīng)用程序中的中間層緩存)能夠?qū)崿F(xiàn)。具體地說(shuō),一般報(bào)告、分析和業(yè)務(wù)智能應(yīng)用程序?qū)⑿枰@種操作方法。
LINQ to DataSet 功能主要通過(guò) DataRowExtensions 和 DataTableExtensions 類(lèi)中的擴(kuò)展方法公開(kāi)。LINQ to DataSet 基于并使用現(xiàn)有的 ADO.NET 2.0 體系結(jié)構(gòu)生成,在應(yīng)用程序代碼中不能替換 ADO.NET 2.0?,F(xiàn)有的 ADO.NET 2.0 代碼將繼續(xù)在 LINQ to DataSet 應(yīng)用程序中有效。
下面看一個(gè)例子:
- // 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("");
- }
使用擴(kuò)展之后的例子:
- // 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("");
- }
【編輯推薦】