C# 3.0新特性初步研究 Part6:使用查询表达式
2024-07-21 02:29:00
供稿:网友
查询表达式(query expression)
大家都应该对sql语句不陌生吧,在c# 2.0之前,嵌入到代码中的sql就是下面这个样子:
1public void test()
2{
3sqlconnection c = new sqlconnection(…);
4 c.open();
5 sqlcommand cmd = new sqlcommand(
6 @“select c.name, c.phone // queries in quotes
7 from customers c
8 where c.city = @p0”
9 );
10 cmd.parameters[“@po”] = “london”; // arguments loosely bound
11 datareader dr = c.execute(cmd);
12 while (dr.read()) {
13 string name = r.getstring(0);
14 string phone = r.getstring(1); // results loosely typed
15 datetime date = r.getdatetime(2); // compiler can’t help catch mistakes
16 }
17 r.close();
18}
在c# 3.0中,我们可以将“sql语句”方便的运用到其他地方,当然这里并不是真正的sql语句~~
我觉得我会在以后的开发过程中使用很多以下的类似代码:
1class program
2 {
3 static void main(string[] args)
4 {
5 var contacts = new list<contact>();
6
7 contacts.add(new contact("michael", "520-331-2718",
8 "33140 sw liverpool lane", "wa"));
9 contacts.add(new contact("jennifer", "503-998-1177",
10 "1245 nw baypony dr", "or"));
11 contacts.add(new contact("sean", "515-127-3340",
12 "55217 sw estate dr", "wa"));
13
14 var wacontacts =
15 from c in contacts
16 where c.state == "wa"
17 select new { c.name, c.phone };
18
19 console.writeline("contacts in the state of washington: ");
20 foreach (var c in wacontacts)
21 {
22 console.writeline("name: {0}, phone: {1}", c.name, c.phone);
23 }
24 }
25 }
26
27 class contact
28 {
29 public string name;
30 public string phone;
31 public string address;
32 public string state;
33
34 public contact(string name, string phone, string address, string state)
35 {
36 this.name = name;
37 this.phone = phone;
38 this.address = address;
39 this.state = state;
40 }
41 }
其中出现的代码:
1var wacontacts =
2 from c in contacts
3 where c.state == "wa"
4 select new { c.name, c.phone };
是否与我们熟悉的sql语句有着极大的相似性呢?of course!
到底是sql梦见了c#,还是c#梦见了sql……