Linq .NET查詢操作淺析
本文向大家介紹Linq .NET查詢操作,可能好多人還不了解Linq .NET查詢操作,沒有關(guān)系,看完本文你肯定有不少收獲,希望本文能教會你更多東西。
Linq .NET查詢操作
除了可以返回數(shù)據(jù)集之外,我們可以使用Linq .NET查詢操作來返回單個或者統(tǒng)計數(shù)據(jù)結(jié)果。下面的例子演示了怎么做:
- <%@ Page Language="C#" CodeFile="Step5.aspx.cs" Inherits="Step5" %>
 - <html>
 - <body>
 - <form id="form1" runat="server">
 - <div>
 - <h1>Aggregate Value Samples</h1>
 - <div>
 - <b>Farthest Distance City:</b>
 - <asp:Label ID="MaxCityNameTxt" runat="server" Text="Label"></asp:Label>
 - <asp:Label ID="MaxCityDistanceTxt" runat="server" Text="Label"></asp:Label>
 - </div>
 - <div>
 - <b>Total Travel Distance (outside of US):</b>
 - <asp:Label ID="TotalDistanceTxt" runat="server" Text="Label"></asp:Label>
 - </div>
 - <div>
 - <b>Average Distance:</b>
 - <asp:Label ID="AverageDistanceTxt" runat="server" Text="Label"></asp:Label>
 - </div>
 - </div>
 - </form>
 - </body>
 - </html>
 
Step5.aspx.cs后臺代碼文件:
- using System;
 - using System.Collections.Generic;
 - using System.Web.UI;
 - using System.Query;
 - public partial class Step5 : System.Web.UI.Page
 - {
 - protected void Page_Load(object sender, EventArgs e)
 - {
 - TravelOrganizer travel = new TravelOrganizer();
 - // Calculate farthest city away
 - Location farthestCity = (from location in travel.PlacesVisited
 - & nbsp; & nbsp; orderby location.Distance descending
 - & nbsp; & nbsp; select location).First();
 - MaxCityNameTxt.Text = farthestCity.City;
 - MaxCityDistanceTxt.Text = "(" + farthestCity.Distance + " miles)";
 - // Calculate total city distances of all cities outside US
 - int totalDistance = (from location in travel.PlacesVisited
 - & nbsp; where location.Country != "USA"
 - & nbsp; select location).Sum(loc => loc.Distance);
 - TotalDistanceTxt.Text = totalDistance + " miles";
 - // Calculate average city distances of each city trip
 - double averageDistance = travel.PlacesVisited.Average(loc => loc.Distance);
 - AverageDistanceTxt.Text = averageDistance + " miles";
 - }
 - }
 
注意,上面最后兩個例子使用了新的Lambda表達(dá)式(Lambda Expression)支持-這些表達(dá)式允許我們通過譬如象委托這樣的代碼段在數(shù)據(jù)之上做進(jìn)一步的操作,從而計算出一個結(jié)果來。你也可以用之來建立你自己的Linq .NET查詢操作(例如:你可以建立一些特定領(lǐng)域的查詢來計算運(yùn)費(fèi)或者收入稅)。所有的對象都是強(qiáng)類型的,而且支 持智能感知和編譯時檢查。
【編輯推薦】















 
 
 
 
 
 
 