代码改变世界

C#3.0(五)--Linq to object(2)操作集合

2011-04-04 19:01  杨延成  阅读(452)  评论(0编辑  收藏  举报

什么都不说了,看代码吧,有问题跟贴!

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TestLinQ2
7{
8 class Student
9 {
10 public string Name
11{
12 set;
13 get;
14 }
15 public int ID
16 {
17 set;
18 get;
19}
20}
21class Program
22 {
23static void Main(string[] args)
24{
25///数组测试
26 ///集合初始化
27 Student[] students = ...{
28 new Student...{Name=\"黄老邪\",ID=1},
29 new Student...{Name=\"洪七公\",ID=2},
30 new Student...{Name=\"欧阳峰\",ID=3}
31 };
32
33 ///这段查询语句的语义是:
34 ///在students中查询姓名为:\"黄老邪\"的学生
35 ///注意返回值s是也是一个集合,他包含多个对象,虽然此查询语句只包含一个
36 //var s = from student in students
37 // where (student.Name.Equals(\"黄老邪\"))
38 // select student;
39
40 ///显示查询结果中第一个元素的姓名
41 //Console.Write(s.First().Name);
42
43 ///查询返回多个结果测试
44 var s = from student in students
45 where (student.ID > 1)
46 select student;
47 IEnumerator<Student> ie = s.GetEnumerator();
48 foreach (var student in s)
49 {
50 Console.WriteLine(student.Name);
51 }
52
53
54
55///List集合测试
56//List students =new List {
57 // new Student{Name=\"黄老邪\",ID=1},
58 // new Student{Name=\"洪七公\",ID=2},
59 // new Student{Name=\"欧阳峰\",ID=3}
60 // };
61
62 //var s = from student in students
63 // where (student.Name.Equals(\"黄老邪\"))
64 // select student;
65
66 //Console.Write(s.First().Name);
67
68
69 /////键值对集合测试
70 //Dictionary students = new Dictionary{
71 // {1, new Student{Name=\"黄老邪\",ID=1}},
72 // {2, new Student{Name=\"洪七公\",ID=2}},
73 // {3, new Student{Name=\"欧阳峰\",ID=3}}
74 // };
75
76 /////注意这时查询语句的变化
77 /////student 代表Dictionary里的一个元素,也就是一个键值对,即有键又有值
78 /////student.Value.Name.Equals(\"黄老邪\")
79
80 //var s = from student in students
81 // where (student.Value.Name.Equals(\"黄老邪\"))
82 // select student.Value;
83
84 //Console.Write(s.First().Name);
85
86 }
87 }
88}