随笔 - 86,  文章 - 0,  评论 - 258,  阅读 - 61969
< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9
查询表达式(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……
posted on 2006-06-10 20:47  NGNGrid  阅读(1085)  评论(3)    收藏  举报
编辑推荐:
· 一个 java 空指针异常的解决过程
· 揭开 SQL Server 和 PostgreSQL 填充因子的神秘面纱
· 没有调度器的协程不是好协程,零基础深入浅出 C++20 协程
· 别做抢活的导演:代码中的抽象层次原则
· 从 Redis 客户端超时到 .NET 线程池挑战
阅读排行:
· 会Vibe Coding的同事:我一个人干掉整个技术部!
· 回答准确率从60%飙至95%!AI知识库救命方案
· dotnetty 内存泄漏的BUG修复了
· 20250709 - GMX V1 攻击事件: 重入漏洞导致的总体仓位价值操纵
· 线上问题定位神器:Arthas
点击右上角即可分享
微信分享提示