本文向大家介绍Linq .NET查询操作,可能好多人还不了解Linq .NET查询操作,没有关系,看完本文你肯定有不少收获,希望本文能教会你更多东西。
Linq .NET查询操作
除了可以返回数据集之外,我们可以使用Linq .NET查询操作来返回单个或者统计数据结果。下面的例子演示了怎么做:
- <%@ 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表达式(Lambda Expression)支持-这些表达式允许我们通过譬如象委托这样的代码段在数据之上做进一步的操作,从而计算出一个结果来。你也可以用之来建立你自己的Linq .NET查询操作(例如:你可以建立一些特定领域的查询来计算运费或者收入税)。所有的对象都是强类型的,而且支 持智能感知和编译时检查。
【编辑推荐】