简单的LINQ例子 学习初期
时间:2010-12-29 来源:吃螺丝
namespace LQ
{
[Table(Name = "Customers")]
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()
{
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;
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();
}
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();
}
}
}