NetFramework3.0中增加了Linq (Language Integrated Query)查询语言。
一 基础知识
1.1 linq 关键词: from ,select,in,where,group by ,order by ...
1.2 linq 注意点:必须以select 或者 group by 结束.
1.3 linq 语义:
from 临时变量 in 集合对象或数据库对象
where 条件表达式
[order by 条件]
select 临时变量中被查询的值
[group by 条件]
1.4 linq分类,按数据源不同分为 linq to object,linq to xml,linq to sql,linq to ado.net
二 示例
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 8, 5, 89, 3, 56, 4, 1, 58 };
var m = from n in arr where n < 5 orderby n select n; //参见1.3linq语义
foreach (var n in m)
{
Console.WriteLine(n);
}
}
}
为什么select放在后面而from放在前面?是为了IDE的智能感知功能.
假如要写Select p.Name, p.Age From p In persons Where xxx ,代码是一个个字符输入的。
我们在写到 p in persons 之前,p 的类型是无法推测的,所以写 Select p. 的时候,Name之类的属性不会弹出智能提示来。
查询示例:
var matchCustomers= from c in db.Customers where c.Country=="USA“
orderby c.City descending
select new {c.CompanyName,c.City};
从db.Customers对象集合中,每个Customer的属性Country值为"USA”,按照City属性由大到小排序,传回以ComanyName和City两个属性的字符串所建立的新对象集合.