using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace LQ
{
[Table(Name = "Customers")] //这里是将数据库中的Customers表映射到Customer类上
public class Customer
{
[Column] //顾名思义 列
public string CustomerID { get; set; }
[Column]
public string City { get; set; }
public override string ToString()
{
return CustomerID + "\t" + City;
}
}
class Program
{
static void Main(string[] args)
{
//NumQuery();
ObjectQuery();
Console.Read();
}
static IEnumerable<Customer> CreateCustomers()
{
return new List<Customer>
{
new Customer{CustomerID="ALFKI",City="Berlin"},
new Customer{CustomerID="BONAP",City="Marseille"},
new Customer{CustomerID="CONSH",City="London"},
new Customer{CustomerID="EASTC",City="London"},
new Customer{CustomerID="FRANS",City="Torino"},
new Customer{CustomerID="LONEP",City="Portland"},
new Customer{CustomerID="NORTS",City="London"},
new Customer{CustomerID="THEBI",City="Portland"}
};
}
static void ObjectQuery()
{
//DataContext 这个东西是LINQ最基本也是最重要的东西 是LINQ to SQL的入口点 详细的请查询MSDN
var db = new DataContext(@"Data Source=SHNI010\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True");
//var results = from c in CreateCustomers()
// where c.City == "London"
// select c.CustomerID;
//LINQ的查询语句
var results = from c in db.GetTable<Customer>()
where c.City == "London"
select c;
db.Log=Console.Out;
foreach (var c in results) //循环结果集
{
Console.WriteLine("{0}\t{1}",c.CustomerID,c.City);
}
Console.Read();
}
//下面这个方法是LINQ对数组的查询 可见LINQ对很多通用
static void NumQuery()
{
var numbers = new int[] { 1,4,9,16,25,36};
var evenNumbers = from p in numbers
where (p % 2) == 0
select p;
Console.WriteLine("Result:");
foreach (var val in evenNumbers)
{
Console.WriteLine(val);
}
Console.Read();
}
}
}