C#自己的数据库语言LINQ(1)
与其他语言不太相同,C#语言本身有着自己的数据库查询语言,叫做LINQ,全称Language-INtegrated Query。
在很大程度上,LINQ与我们常用的SQL是相通的,但是却有着更加独特的一些特性。由于程序员每天都要对内存、数据库或是XML文件中的数据对象进行查找和存取,但SQL语言同编程语言的分离为这种行为造成了很大的困扰。
而LINQ作为一种连接面向对象语言和关系数据库的桥梁,联合了对内存、数据库和XML的数据处理。同时作为C#的一种内部语言,写法上更有利于C#程序员操作。
1 // Example13-1.A simple LINQ query 2 using System; 3 using System.Collections.Generic; 4 using System.Linq; 5 namespace Programming_CSharp 6 { 7 // Simple customer class 8 public class Customer 9 { 10 public string FirstName { get; set; } 11 public string LastName { get; set; } 12 public string EmailAddress { get; set; } 13 // Overrides the Object.ToString() to provide a 14 // string representation of the object properties. 15 public override string ToString() 16 { 17 return string.Format("{0} {1}\nEmail: {2}", 18 FirstName, LastName, EmailAddress); 19 } 20 }
上面的代码使用了System.Linq的命名空间,同时定义了Customer类的一些成员元素。
1 // Create a customer list with sample data 2 private static List<Customer> CreateCustomerList() 3 { 4 List<Customer> customers = new List<Customer> 5 { 6 new Customer { FirstName = "Orlando“,LastName = "Gee", 7 EmailAddress = "orlando0@adventure-works.com"}, 8 new Customer { FirstName = "Keith“, LastName = "Harris", 9 EmailAddress = "keith0@adventure-works.com" }, 10 new Customer { FirstName = "Donna“, LastName = "Carreras", 11 EmailAddress = "donna0@adventure-works.com" }, 12 new Customer { FirstName = "Janet“, LastName = "Gates", 13 EmailAddress = "janet1@adventure-works.com" }, 14 new Customer { FirstName = "Lucy“, LastName = "Harrington", 15 EmailAddress = "lucy0@adventure-works.com" } 16 }; 17 return customers; 18 }
上述代码在内存中构成了Customer的数据集合,换言之将数据保存到了内存之中。
1 public class Tester 2 { 3 static void Main() // Main program 4 { 5 List<Customer> customers = CreateCustomerList(); 6 // Find customer by first name 7 IEnumerable<Customer> result = from customer in customers 8 where customer.FirstName == "Donna“ 9 select customer; 10 Console.WriteLine("FirstName == \"Donna\""); 11 foreach (Customer customer in result) 12 { Console.WriteLine(customer.ToString());} 13 customers[3].FirstName = "Donna"; 14 Console.WriteLine("FirstName == \"Donna\" (take two)"); 15 foreach (Customer customer in result) 16 { Console.WriteLine(customer.ToString());} 17 } 18 } 19 }//namespace
上述代码中,使用了LINQ查询语句对数据进行了操作。注意:真正的操作开始于foreach语句,LINQ语句被“保存”到result中,在foreach中被调用。
LINQ的基础介绍到此为止,下次我们再来一起学习LINQ的详细知识。