• 光脚丫学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# 逻辑 ANDOR 运算符来根据需要在 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;  
    
  • 相关阅读:
    RabbitMQ:六、网络分区
    RabbitMQ:五、高阶
    RabbitMQ:四、跨越集群
    数据结构:红黑树
    RabbitMQ:三、进阶
    面对对象多态的异常
    面向对象三大特征---多态
    面对对象继承的优点和缺点
    面对对象当中的代码块
    面对对象this关键字
  • 原文地址:https://www.cnblogs.com/GJYSK/p/1863789.html
Copyright © 2020-2023  润新知