Linq是一种.Net特有的查询语言,是一组用于c#或vb语言的扩展,它允许编写以查询数据库相同的方式操作内存数据。说白了,它就是SQL语法相似的一种查询内存数据的语法,只不过,SQL是查数据库,它是查询数据库或内存数据。
语义:
from 临时变量 in 集合对象或数据库对象
where 条件表达式 [order by 条件]
select 临时变量被查询的值
[group by 条件]
Linq的查询返回值的类型是临时变量的类型,可能是一个对象也可能是一个集合。并且Linq的查询表达式是在最近一次创建对象时才被编译的。Linq查询一般是一个延时查询,只有真正调用查询结果的时候,才会进行查询。
看下面代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
class Program { static void Main( string [] args) { IList<Person> lists = new List<Person>(); //插入测试数据 for ( int i = 0; i < 20; i++) { Person p = new Person(); p.Age = new Random(i).Next(1, 100); p.Name = "Name" + new Random(i).Next(1, 10); p.ID = i + 1; lists.Add(p); } //查询lists中Age>18的所有记录,按ID降序排列 var result = from person in lists //person为lists集合的项 where person.Age > 18 //where条件 orderby person.ID descending //按ID降序排列 select person; //查询结果的值 //输出结果 Console.WriteLine( "查询lists中Age>18的所有记录,按ID降序排列" ); foreach (Person p in result) { Console.WriteLine( string .Format( "ID:{0}\tName:{1}\tAge:{2}" , p.ID, p.Name, p.Age)); } } } public class Person { public int ID { get ; set ; } public string Name { get ; set ; } public int Age { get ; set ; } } |
结果:
从上面例子不难理解Linq的查询方式跟sql或者hibernate的hql非常相似。只是多了个in,并且条件中可以使用c#语法判断。总之,linq可以说是一种很优雅的查询语言,同理,我们在上一篇ADO.NET Entity Framework中也可使用这个进行查询操作