光脚丫学LINQ(002):筛选数据
视频演示:http://u.115.com/file/f2cf72dc9e
也许最常用的查询操作是应用布尔表达式形式的筛选器。此筛选器使查询只返回那些表达式结果为 true 的元素。使用 where 子句生成结果。实际上,筛选器指定从源序列中排除哪些元素。在下面的示例中,只返回那些地址位于伦敦的 customers。
NorthwindDataContext db = new NorthwindDataContext(); var LondonCustomers = from Customer in db.Customers where Customer.City == "London" select Customer; foreach (var Customer in LondonCustomers) { Console.WriteLine("---------------------"); Console.WriteLine("Customer ID : {0}", Customer.CustomerID); Console.WriteLine("Customer Name : {0}", Customer.ContactName); Console.WriteLine("City : {0}", Customer.City); } NorthwindDataContext db = new NorthwindDataContext(); var LondonCustomers = from Customer in db.Customers where Customer.City == "London" select Customer; foreach (var Customer in LondonCustomers) { Console.WriteLine("---------------------"); Console.WriteLine("Customer ID : {0}", Customer.CustomerID); Console.WriteLine("Customer Name : {0}", Customer.ContactName); Console.WriteLine("City : {0}", Customer.City); }
您可以使用熟悉的 C# 逻辑 AND 和 OR 运算符来根据需要在 where 子句中应用任意数量的筛选表达式。例如,若要只返回位于“伦敦”AND 姓名为“Thomas Hardy”的客户,您应编写下面的代码:
var LondonCustomers = from Customer in db.Customers where Customer.City == "London" && Customer.ContactName == "Thomas Hardy" select Customer; var LondonCustomers = from Customer in db.Customers where Customer.City == "London" && Customer.ContactName == "Thomas Hardy" select Customer;
若要返回位于伦敦或巴黎的客户,您应编写下面的代码:
var LondonCustomers = from Customer in db.Customers where Customer.City == "London" || Customer.City == "Paris" select Customer;