如何:使用 LINQ 計算、總和或平均數據 (Visual Basic)
Language-Integrated 查詢 (LINQ) 可讓您輕鬆存取資料庫資訊並執行查詢。
下列範例示範如何建立對 SQL Server 資料庫執行查詢的新應用程式。 範例會使用 Aggregate
和 Group By
子句來計算、加總及平均結果。 如需詳細資訊,請參閱 Aggregate 子句 和 Group By 子句。
本文中的範例會使用 Northwind 範例資料庫。 若要取得資料庫,請參閱 下載範例資料庫。。
注意
您的電腦可能會在下列指示中顯示某些 Visual Studio 使用者介面元素的不同名稱或位置。 您擁有的 Visual Studio 版本,以及您所使用的設定會決定這些元素。 如需詳細資訊,請參閱 個人化 IDE。
建立資料庫的連線
在 Visual Studio 中,單擊 [檢視] 功能表上的 [伺服器總管]/[資料庫總管],以開啟 [伺服器總管]/[資料庫總管]。
在 [伺服器總管]/[資料庫總管] 中,以滑鼠右鍵按兩下 [資料連線],然後按兩下 [[新增連線]。
請指定有效連線至 Northwind 範例資料庫。
加入包含 LINQ to SQL 檔案的專案
在 Visual Studio 的 [檔案] 功能表上,選擇 [新增],然後單擊 [專案]。 選取 Visual Basic Windows Forms 應用程式 作為項目類型。
在 [專案] 功能表上,按一下 [新增項目]。 選取 LINQ to SQL 類別 項目範本。
將檔案命名為
northwind.dbml
。 按一下新增。 對象關係型設計工具 (O/R 設計工具) 已針對 northwind.dbml 檔案開啟。
若要將數據表加入至 O/R 設計工具查詢
在 [伺服器總管]/[資料庫總管]中,展開與 Northwind 資料庫的連線。 展開 [數據表] 資料夾。
如果您已關閉 O/R 設計工具,您可以按兩下您稍早新增的 northwind.dbml 檔案來重新開啟它。
按兩下 [客戶] 資料表,並將其拖曳至設計工具的左窗格。 單擊 [Orders] 資料表,並將它拖曳至設計工具的左窗格。
設計工具會為專案建立新的
Customer
和Order
物件。 請注意,設計工具會自動偵測數據表之間的關聯性,並建立相關物件的子屬性。 例如,IntelliSense 會顯示Customer
物件具有與該客戶相關的所有訂單Orders
屬性。儲存變更並關閉設計工具。
儲存您的專案。
若要新增程式代碼來查詢資料庫並顯示結果
從 [工具箱],將 DataGridView 控件拖曳至專案 Form1 的預設 Windows Form。
雙擊表單1,將程式碼添加至表單的
Load
事件。當您將數據表新增至 O/R 設計工具時,設計工具會為專案新增 DataContext 物件。 此物件包含您必須存取這些數據表的程式代碼,以及存取每個數據表的個別物件和集合。 專案的 DataContext 物件會根據 .dbml 檔案的名稱來命名。 針對此項目,DataContext 物件會命名為
northwindDataContext
。您可以在程式代碼中建立 DataContext 的實例,並查詢 O/R 設計工具所指定的數據表。
將下列程式碼新增至
Load
事件,以查詢作為 DataContext 屬性公開的數據表,並對查詢結果進行計數、求和及平均值計算。 此範例會使用Aggregate
子句來查詢單一結果,而Group By
子句會顯示群組結果的平均值。Dim db As New northwindDataContext Dim msg = "" Dim londonCustomerCount = Aggregate cust In db.Customers Where cust.City = "London" Into Count() msg &= "Count of London Customers: " & londonCustomerCount & vbCrLf Dim averageOrderCount = Aggregate cust In db.Customers Where cust.City = "London" Into Average(cust.Orders.Count) msg &= "Average number of Orders per customer: " & averageOrderCount & vbCrLf Dim venezuelaTotalOrders = Aggregate cust In db.Customers Where cust.Country = "Venezuela" Into Sum(cust.Orders.Count) msg &= "Total number of orders from Customers in Venezuela: " & venezuelaTotalOrders & vbCrLf MsgBox(msg) Dim averageCustomersByCity = From cust In db.Customers Group By cust.City Into Average(cust.Orders.Count) Order By Average DataGridView1.DataSource = averageCustomersByCity 'Another way to grab the count and sum londonCustomerCount = (From cust in db.Customers Where cust.City = "London").Count() venezuelaTotalOrders = (From cust in db.Customers Where cust.Country = "Venezuela" Select cust.Orders).Sum()
按 F5 執行您的項目並檢視結果。