查询表达式(Query Expression)
大家都应该对SQL语句不陌生吧,在C# 2.0之前,嵌入到代码中的SQL就是下面这个样子:
在C# 3.0中,我们可以将“SQL语句”方便的运用到其他地方,当然这里并不是真正的SQL语句~~
我觉得我会在以后的开发过程中使用很多以下的类似代码:
其中出现的代码:
是否与我们熟悉的SQL语句有着极大的相似性呢?Of Course!
到底是SQL梦见了C#,还是C#梦见了SQL……
大家都应该对SQL语句不陌生吧,在C# 2.0之前,嵌入到代码中的SQL就是下面这个样子:
1
public void Test()
2
{
3
SqlConnection 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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

在C# 3.0中,我们可以将“SQL语句”方便的运用到其他地方,当然这里并不是真正的SQL语句~~
我觉得我会在以后的开发过程中使用很多以下的类似代码:
1
class 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
}

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

32

33

34

35

36

37

38

39

40

41

其中出现的代码:
1
var WAContacts =
2
from c in contacts
3
where c.State == "WA"
4
select new { c.Name, c.Phone };

2

3

4

是否与我们熟悉的SQL语句有着极大的相似性呢?Of Course!
到底是SQL梦见了C#,还是C#梦见了SQL……
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述