.NET Framework 3.5中的LINQ简介

1. LINQ 概览

 1.1. 数据访问现状

 1.2. LINQ 数据访问方式

 1.3. LINQ 项目

2. 访问数组

 2.1. 查询数组

 2.2. 绑定到页面

3. 访问集合

 3.1. 自定义 City 类

public class City
{
public string Name;
public string Country;
public int DistanceFromSeattle;
}
List<City> locations = GetLocations();

 3.2. 查询City 集合

 3.3. 绑定到页面

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField HeaderText="Country" DataField="Country" />
<asp:BoundField HeaderText="City" DataField="Name" />
<asp:BoundField HeaderText=“Dist” DataField="DistanceFromSeattle“/>
</Columns>
</asp:GridView>

 3.4. 绑定页面结果

4. 查询投影

 4.1. 查询投影(Select)

  • 不返回所有数据列/属性
  • 修改或者转化查询返回的数据
  • 利用编译器对“匿名类型”的支持查询数据列/属性
  • 生成匿名类型(’a)

 4.2. 使用匿名类型

 4.3. 匿名类型绑定

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField HeaderText="Country" DataField="Country" />
<asp:BoundField HeaderText="City" DataField=“City" />
<asp:BoundField HeaderText="Dist (KM)" DataField="DistanceInKm" />
</Columns>
</asp:GridView>

 4.4. 匿名类型绑定结果

5. 使用 λ 表达式

 5.1. 使用λ 表达式

 • 查询语法是一个方便的声明性代码缩写您,可以手动编写它:
 • IEnumerable expr = names
  .Where(s => s.Length == 5)
  .OrderBy(s => s)
  .Select(s => s.ToUpper());

 5.2. λ 表达式的委托声明
 • λ 表达式是C# 2 0 匿名方法的自然演化结果

Func filter = delegate (string s) {
return s.Length == 5;
};
Func extract = delegate (string s) {
return s;
};
Func project = delegate (string s) {
return s.ToUpper();
};
IEnumerable expr = names.Where(filter)
.OrderBy(extract)
.Select(project);

 5.3. 表达式树
 . 表达式树是λ 表达式的有效内存中数据表示形式,它使表达式的结构透明且显式。
 . 将λ 表达式指定给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);

6. 查询操作符

 6.1. 查询操作符Where 的定义

public static class Sequence {
  public static IEnumerable Where(
this IEnumerable source,
Func predicate) {
foreach (T item in source)
if (predicate(item))
yield return item;
}
}

 6.2. 调用
 • 普通的方式来调用扩展方法:
 • IEnumerable<string> query =Enumerable.Where(names,s => s.Length < 6);
 • C#语言允许我们使用如下的方式来调用扩展方法:
 • IEnumerable<string> query = names.Where(s =>s.Length < 6);

 6.3. 标准查询操作符
 . 排序与分组
  – OrderBy & GroupBy
 . 聚合
  – Count
  – Sum
  – Average
  – Max
  – Min
 . 投影
  – Select & SelectMany

 6.3. 查询语法
 • C# 的现有 foreach 语句通过 .NET Framework 的IEnumerable/IEnumerator 方法为迭代提供声明
性语法。foreach 语句完全是可选的,但经过证实,它是一个非常方便和常用的语言机制。
 • 查询语法通过声明性语法为以下最常用的查询操作符简化了查询表达式:Where、Select、
SelectMany、GroupBy、OrderBy、ThenBy、OrderByDescending 和ThenByDescending。

 

posted @ 2017-09-02 23:00  tiger_yj  阅读(512)  评论(0编辑  收藏  举报