Linq初级学习 [标准查询操作符的使用和调用]

标准查询操作符

本文章是我最近学习Linq的一些示例,分享给和我一样刚开始接触Linq的朋友们作为一个参考,因为是初学,肯定有很多不足,因此希望大家友善提醒,切勿针锋相对,我会及时改正的~~

目录:

01 投影操作符(Select,SelectMany)

02 限制操作符(Where)

03 排序操作符(OrderBy,OrderByDescending,ThenBy,ThenByDescending,Reverse)

04 联接操作符(join,GroupJoin)

05 分组操作符(GroupBy)

06 串联操作符(Concat)

07 聚合操作符(Aggregate,Average,Count,LongCount,Max,Min,Sum)

08 集合操作符(Distinct,Union,Intersect,Except)

09 生成操作符(Empty,Range,Repeat)

10 转换操作符(Cast,OfType,ToArray,ToDictionary,ToList,ToLookup)

11 元素操作符(DefaultIfEmpty,ElementAt,ElementAtOrDefault,First,Last,FirstOrDefault,LastOrDefault,Single,SingleOrDefault)

12 相等操作符(SequenceEqual)

13 量词操作符(All,Any)

14 分割操作符(Skip,SkipWhile,Take,TakeWhile)

 

01.投影操作符(Select,SelectMany)

(1)Select操作符对单个序列或者集合中的值进行投影,可以控制从序列中返回指定的列.

方法语法:

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data.Linq;
6
7 namespace ConsoleApplication1
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 //创建测试数据
14 User[] users = new User[]{
15 new User(){ Id = 1, FirstName = "Huang", LastName = "Cong", Age = 12},
16 new User(){ Id = 2, FirstName = "Yang", LastName = "Qiu", Age = 22},
17 new User(){ Id = 3, FirstName = "Cai", LastName = "Zheng", Age = 18},
18 new User(){ Id = 4, FirstName = "Huang", LastName = "Chao", Age = 32},
19 new User(){ Id = 5, FirstName = "Teng", LastName = "Jie", Age = 12},
20 new User(){ Id = 6, FirstName = "Liang", LastName = "Zhi", Age = 8}
21 };
22 //使用Select操作符进行投影,对序列只返回First一个列
23 var query = users.Select(u => new { u.FirstName });
24 //输出
25 foreach (var q in query)
26 Console.WriteLine(q.FirstName);
27 }
28 }
29 class User
30 {
31 public int Id { get; set; }
32 public string FirstName { get; set; }
33 public string LastName { get; set; }
34 public int Age { get; set; }
35 public override string ToString()
36 {
37 return String.Format("Id:{0}\tFirstName:{1}\tLastName:{2}\tAge:{3}", this.Id, this.FirstName, this.LastName, this.Age);
38 }
39 }
40 }

查询语法:

var query = from u in users select new { u.FirstName };

运行结果:


 

posted @ 2011-11-14 15:25  lanmiao  阅读(164)  评论(0编辑  收藏  举报