LINQ有很多值得学习的地方,这里我们主要介绍LINQ匿名类型,包括介绍新建一个具有City和Distance 两个属性的LINQ匿名类型来实现等方面
LINQ匿名类型(Anonymous Types)
LINQ能够利用的另一个C#和VB新特性之一就是对“LINQ匿名类型”的支持。这允许你不需明确声明对象模型就能很容易地创建和使用内联的类型结构,因为类型可以通过数据的初始 化推断出来。这在使用LINQ查询“自定义构形(custom shape)”数据时非常的有用。
例如,考虑这样一个场景:你正在处理一个具有许多属性的数据库或者强类型的集合-但是你只关心其中少数的 几个字段。与创建和处理整个类型相比,仅返回你所需要的字段将会更加有用些。我们来新建一个"step6.aspx"文件来实现以上操作:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Step6.aspx.cs" Inherits="Step6" %>
<html>
<body>
<form id="form1" runat="server">
<div>
<h1>Anonymous Type</h1>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
在我们的后台代码文件中我们将编写一个使用LINQ匿名类型的LINQ查询,如下所示:
using System;
using System.Web.UI;
using System.Query;
public partial class Step6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TravelOrganizer travel = new TravelOrganizer();
GridView1.DataSource = from location in travel.PlacesVisited
& nbsp; orderby location.City
& nbsp; select new {
& nbsp; & nbsp;City = location.City,
& nbsp; & nbsp;Distance = location.Distance
& nbsp; };
GridView1.DataBind();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
注意,我们并没有像上面一样从select子句中返回一个"location"对象,我们通过新建一个具有City和Distance 两个属性的LINQ匿名类型来实现。这两个属性的类型是根据它们初始化时赋与的值来自动确定的,在这里是一个是 string,另一个是int。
【编辑推荐】