您的位置:首页 > 其它

NET Framework 3 5中的 LINQ 简介

2010-12-07 20:15 204 查看
NET Framework 3 5中的 LINQ 简介

本次课程内容包括

? LINQ 概览

? 访问数组 ? 访问集合 ? 查询投影

? 使用λ 表达式 ? 查询操作符

议程

? LINQ 概览 ? 访问数组 ? 访问集合 ? 查询投影

? 使用λ 表达式 ? 查询操作符

数据访问的问题

数据 != 对象

数据访问现状

SqlConnection c = new SqlConnection(…);

Queries in quotes

c.Open();

SqlCommand cmd = new SqlCommand(

@"SELECTc.Name, c.Phone

Arguments

FROM Customers c

loosely bound

WHERE c City = @p0"

);

cmd.Parameters.AddWithValue("@po", "London");DataReader dr = c.Execute(cmd);

Results loosely

while (dr.Read()) {

typed

string name = dr.GetString(0); string phone =dr.GetString(1)

DateTimedate = dr.GetDateTime(2) } dr.Close();

Compilercannot help

catch mistakes

LINQ 数据访问方式

Classes describe

public class Customer

data

{

public int CustomerId;

Encapsulated

public string Name;

Business

public string City;

Validation

public void Validate() {

Query is natural

// Todo: Add Business Validation

part of the

}

language

}

GridView1.DataSource = from customer in db.Customers

wherecustomer.City == "London"

select customer;

The compiler

provides

GridView1 DataBind();

intellisense and

type-checking

LINQ 项目

C#

VB

Others…

.Net Language Integrated Query (LINQ)

LINQ enabled data sources

LINQ enabled ADO.NET

LINQ

LINQ

LINQ

LINQ

LINQ

To Objects

To Datasets

To SQL

To Entities

To XML

<book>

<title/>

<author/><price/>

</book>

Objects

Relational

XML

议程

? LINQ 概览

? 访问数组

? 访问集合 ? 查询投影

? 使用λ 表达式 ? 查询操作符

查询数组

Array implements

IEnumerable<T>

string [] cities = { “Auckland”, “Oslo”, “Sydney”,

“Seattle”, “Paris”, “Los Angeles” };

IEnumerable<string> places = from city in cities

wherecity.Length > 5

orderby city descending select city;

GridView1.DataSource = places; GridView1.DataBind();

LINQ Query

Expression using

Query Operators

IEnumerable<string>

sequence result can be

used w/ databinding

绑定到页面

议程

? LINQ 概览 ? 访问数组

? 访问集合

? 查询投影

? 使用λ 表达式 ? 查询操作符

自定义 City 类

public class City {

public string Name;

public string Country;

public int DistanceFromSeattle;

}

List<City> locations = GetLocations();

查询 City 集合

Collection implements

IEnumerable<T>

List<City> locations = GetLocations();

IEnumerable<City> places = from city in locations

wherecity.DistanceFromSeattle > 1000 orderby city.Country, city.Name selectcity;

GridView1.DataSource = places; GridView1.DataBind();

IEnumerable<City> return sequencedetermined by select statement

绑定到页面

<asp:GridView ID="GridView1"AutoGenerateColumns="false" runat="server">

<Columns>

<asp:BoundFieldHeaderText="Country" DataField="Country" /> <asp:BoundFieldHeaderText="City" DataField="Name" /> <asp:BoundField HeaderText=“Dist”DataField="DistanceFromSeattle“/>

</Columns>

</asp:GridView>

绑定页面结果

议程

? LINQ 概览 ? 访问数组 ? 访问集合

? 查询投影

? 使用λ 表达式 ? 查询操作符

查询投影(Select)

? 不返回所有数据列/属性 ? 修改或者转化查询返回的数据

? 利用编译器对“匿名类型”的支持查询数

据列/属性

? 生成匿名类型(’a)

使用匿名类型

List<City> cities = CityUtilityHelper.GetCities();

var places = from city in cities

where city.DistanceFromSeattle > 1000 select new {

City = city.Name,

Country = city.Country,

DistanceInKm = city.DistanceFromSeattle * 1.61

};

GridView1.DataSource = places; GridView1.DataBind();

Anonymous type used to custom shape dataresults and apply miles->kilometer conversion

匿名类型绑定

<asp:GridView ID="GridView1"AutoGenerateColumns="false" runat="server">

<Columns>

<asp:BoundFieldHeaderText="Country" DataField="Country" /> <asp:BoundFieldHeaderText="City" DataField=“City" /> <asp:BoundFieldHeaderText="Dist (KM)"DataField="DistanceInKm" />

</Columns>

</asp:GridView>

匿名类型绑定结果

议程

? LINQ 概览 ? 访问数组 ? 访问集合 ? 查询投影

? 使用λ 表达式 ? 查询操作符

使用 λ表达式

? 查询语法是一个方便的声明性代码缩写, 您

可以手动编写它:

? IEnumerable expr = names

.Where(s => s.Length == 5)

.OrderBy(s => s)

.Select(s => s.ToUpper());

λ 表达式的委托声明

? λ表达式是 C# 2.0 匿名方法的自然演化结果

Func filter = delegate (string s) {

return s.Length == 5;

};

Func extract = delegate (string s) {

returns;

};

Func project = delegate (string s) {

returns.ToUpper();

};

IEnumerable expr = names.Where(filter)

.OrderBy(extract)

.Select(project);

表达式树

? 表达式树是λ 表达式的有效内存中数据表示

形式,它使表达式的结构透明且显式。 ? 将 λ 表达式指定给 Expression 类型的变量

、字段或参数,则编译器将发出表达式树。

BinaryExpression body = (BinaryExpression)filter.Body; ParameterExpression left = (ParameterExpression)body.Left;ConstantExpression right =(ConstantExpression)body.Right;

Console.WriteLine("{0} {1} {2}",left.Name, body.NodeType,right.Value);

查询操作符 Where 的定义

? public static class Sequence {

publicstatic IEnumerable Where( this IEnumerable source, Func predicate) {

foreach (T item in source)

if(predicate(item))

yield return item;

}

}

调用

? 普通的方式来调用扩展方法:

? IEnumerable<string> query =

Enumerable.Where(names,s => s.Length< 6);

? C#语言允许我们使用如下的方式来调用扩展

方法:

? IEnumerable<string> query = names.Where(s =>

s.Length< 6);

议程

? LINQ 概览 ? 访问数组 ? 访问集合 ? 查询投影

? 使用λ 表达式

? 查询操作符

标准查询操作符

? 排序与分组

- OrderBy & GroupBy

? 聚合

- Count - Sum

- Average - Max

- Min

? 投影

Select & SelectMany

查询语法

? C#的现有 foreach 语句通过 .NET Framework 的

IEnumerable/IEnumerator方法为迭代提供声明 性语法。foreach 语句完全是可选的,但经过证实, 它是一个非常方便和常用的语言机制。

? 查询语法 通过声明性语法为以下最常用的查询操

作符简化了查询表达式:Where、Select、 SelectMany、GroupBy、OrderBy、ThenBy、 OrderByDescending 和 ThenByDescending。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: