LINQ(Language-INtegrated Query) 是一种用作查找、存取数据库或XML文件的语言模式。
是沟通面向对象语言与数据库的方式。与SQL很相似。
using System; using System.Collections.Generic; using System.Linq; //linq namespace namespace Programming_CSharp { // Simple customer class public class Customer //定义customer对象,构成要搜索的集合 { public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } // Overrides the Object.ToString() to provide a // string representation of the object properties. public override string ToString() { return string.Format("{0} {1}\nEmail: {2}", FirstName, LastName, EmailAddress); } }
// Create a customer list with sample data private static List<Customer> CreateCustomerList() { List<Customer> customers = new List<Customer> { new Customer { FirstName = "Orlando“,LastName = "Gee", EmailAddress = "[email protected]"}, new Customer { FirstName = "Keith“, LastName = "Harris", EmailAddress = "[email protected]" }, new Customer { FirstName = "Donna“, LastName = "Carreras", EmailAddress = "[email protected]" }, new Customer { FirstName = "Janet“, LastName = "Gates", EmailAddress = "[email protected]" }, new Customer { FirstName = "Lucy“, LastName = "Harrington", EmailAddress = "[email protected]" } }; return customers; }
// 内存中构成Customer的集合
static void Main() // Main program { List<Customer> customers = CreateCustomerList(); // Find customer by first name IEnumerable<Customer> result = from customer in customers where customer.FirstName == "Donna" select customer; //select 放在最后 Console.WriteLine("FirstName == \"Donna\""); foreach (Customer customer in result) { Console.WriteLine(customer.ToString());} //显示结果 customers[3].FirstName = "Donna"; //修改数据 Console.WriteLine("FirstName == \"Donna\" (take two)"); //显示结果 foreach (Customer customer in result) { Console.WriteLine(customer.ToString());} } } }//namespace
Join 关键字
内连关键字 将两个数据表连接连接
[data source 1] join [data source 2] on [join condition]
LINQ中含有关键字
where from select等
与SQL类似的 where表示筛选条件
from 表示指定的范围
select 表示查找映射
Var关键字
var通用数据类型 必须初始化
var num = 1234; var strnum = "1234"; var classsimple = new class1;
时间: 2024-09-29 07:14:17