一、linq查询可以做什么

    linq表达式可以从数据源(这里好似一个int[])中,按照一定条件(where语句指定)检索数据,生成一个新的序列,但是不改变单个元素。然后可以根据各种方式对返回的序列进行排序或者分组。

1 namespace LinqExpress
2 {
3 class Program
4 {
5 private static int[] strocs = { 75, 80, 98, 78, 86, 65, 50, 90 };
6 static void Main(string[] args)
7 {
8 var highScoresQuery = from stroc in strocs
9 orderby stroc ascending
10 where stroc > 80
11 select stroc;
12 foreach (var stroc in highScoresQuery)
13 {
14 Console.WriteLine(stroc);
15 }
16 Console.ReadLine();
17
18 }
19 }
20 }

      linq表达式可以对查询的数据进行加工封装或者转换成新的类型。例如上面的例子我们只是返回了一个int集合,如果没有上下文信息我们很难分辨这个结果表示什么,利用linq表达式的Select子句可以将查询记过格式化成String类型的描述信息的集合。我们甚至可以从一条记录中检索特定的信息然后构建一个新的对象类型。

var highScoresQuery = from stroc in strocs
orderby stroc ascending
where stroc > 80
select
string.Format("分数:{0}",stroc);

      linq表达式可以查询关于数据源信息的单一的值,例如,符合某个条件的元素的数量,具有最大值或最小值的元素以及类似于sql中聚合函数的信息。下面得到大于80的分数的数量:

int highScoreCount =
(from score
in scores
where score > 80
select score)
.Count();

     查询表达式必须以 from 子句开头,并且必须以 selectgroup 子句结尾。在第一个 from 子句和最后一个 selectgroup 子句之间,查询表达式可以包含一个或多个下列可选子句:whereorderbyjoinlet 甚至附加的 from 子句。还可以使用 into 关键字使 joingroup 子句的结果能够充当同一查询表达式中附加查询子句的源。

 posted on 2011-06-05 23:16  小段段  阅读(596)  评论(0编辑  收藏  举报