概述

LINQ,语言集成查询(Language INtegrated Query)是一组用于c#和Visual Basic语言的扩展。它允许编写C#或者Visual Basic代码以查询数据库相同的方式操作内存数据。LINQ定义了大约40个查询操作符,如select、from、in、where以及order by(C#)中。使用这些操作可以编写查询语句。不过,这些查询还可以基于很多类型的数据,每个数据类型都需要一个单独的LINQ类型。唯一的要求是项目应面向 .NET Framework 3.5 或更高版本。

 

 

查询操作三部分

下面示例代表着1,2,3

 1 class IntroToLINQ
 2 {        
 3     static void Main()
 4     {
 5         // The Three Parts of a LINQ Query:
 6         //  1. Data source.
 7         int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
 8 
 9         // 2. Query creation.
10         // numQuery is an IEnumerable<int>
11         var numQuery =
12             from num in numbers
13             where (num % 2) == 0
14             select num;
15 
16         // 3. Query execution.
17         foreach (int num in numQuery)
18         {
19             Console.Write("{0,1} ", num);
20         }
21     }
22 }

  下图是完整的查询过程

Linq学习第一天

在上例中由于数据源是数组,数组隐式支持了IEnumerable(Of T)

 

 

数据源

例如,LINQ to XML 将 XML 文档加载到可查询的 XElement 类型中:

1 // Create a data source from an XML document.
2 // using System.Xml.Linq;
3 XElement contacts = XElement.Load(@"c:\myContactList.xml");

  支持非泛型IEnumeable接口的类型(如 ArrayList)也可用作 LINQ 数据源。

 

 

查询

为使编写查询的工作变得更加容易,C# 引入了新的查询语法。

 

标准查询运算符概述

 

延迟执行

 

此概念称为“延迟执行”,下面的示例对此进行了演示:

 

 

1 //  Query execution. 
2 foreach (int num in numQuery)
3 {
4     Console.Write("{0,1} ", num);
5 }

 

num 保存了返回的序列中的每个值(一次保存一个值)。

在应用程序中,可以创建一个检索最新数据的查询,并可以按某一时间间隔反复执行该查询以便每次检索不同的结果。

 

 

强制立即执行

下面的查询返回源数组中偶数的计数:

1 var evenNumQuery = 
2     from num in numbers
3     where (num % 2) == 0
4     select num;
5 
6 int evenNumCount = evenNumQuery.Count();

 若要强制立即执行任意查询并缓存其结果,可以调用 ToList(Of TSource)    或 ToArray(Of TSource)方法。

 1 List<int> numQuery2 =
 2     (from num in numbers
 3      where (num % 2) == 0
 4      select num).ToList();
 5 
 6 // or like this:
 7 // numQuery3 is still an int[]
 8 
 9 var numQuery3 =
10     (from num in numbers
11      where (num % 2) == 0
12      select num).ToArray();

 但是,通过调用 ToListToArray,也可以将所有数据缓存在单个集合对象中。

 

 

相关文章:

  • 2021-11-28
  • 2021-11-24
  • 2021-06-16
  • 2021-11-28
  • 2021-08-27
  • 2021-09-12
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-09
  • 2022-12-23
  • 2021-07-25
  • 2021-12-05
  • 2021-12-15
相关资源
相似解决方案