【问题标题】:AND Condition using LINQ使用 LINQ 的 AND 条件
【发布时间】:2012-10-11 14:01:15
【问题描述】:

我有一份客户名单:

List<customer> customerList;

我只想获得 Country="India" 和 Status="A" 的客户。

我试过这个:

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India") && p.Status.Equals("A")).ToList();

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India")).Where(p=>p.Status.Equals("A")).ToList();

但都没有返回任何东西。

如果我像下面的例子那样划分条件,那么记录被正确获取。

List<customer> customerList=customerList.Where(p=>p.Country.Equals("India")).ToList();
customerList=customerList.Where(p=>p.Status.Equals("A")).ToList();

我想知道如何在单个查询中使用 AND 条件过滤对象。

谁能告诉,有什么好办法,而不是调用 where 条件。

【问题讨论】:

  • 您确定至少有一个项目同时满足这两个条件吗?您的前 2 个查询对我来说似乎是正确的......
  • 显示您的测试数据,因为这 2 个 linq 语句看起来是正确的。
  • CountryStatus 是字符串变量,还是其他类型?
  • 您能否考虑将答案标记为正确甚至完全回复?

标签: c# asp.net linq list


【解决方案1】:

在这种情况下不要使用.Equals。使用相等运算符 (==)。

customerList.Where(p=>p.Country == "India" && p.Status == "A").ToList();

Jon Skeet 文章 - When should I use == and when should I use Equals?

对于值类型,我通常使用 == 来获得更易于阅读的代码。事物 如果值类型为 == which 提供了重载,将会变得棘手 与 Equals 的行为不同,但我认为这种类型非常糟糕 设计开始。

但是,您绝对需要确保您的列表确实已填充。

【讨论】:

    【解决方案2】:

    这按预期工作,所以我不知道你在做什么,但你原来的方法是正确的。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication4 {
        public class Customer {
            public string Country { get; set; }
            public string Status { get; set; }
        }
    
        class Program {
            static void Main(string[] args) {
                var list = new List<Customer>();
                list.Add(new Customer() { Country = "India", Status = "A" });
                list.Add(new Customer() { Country = "USA", Status = "A" });
    
                var results = list.Where((c) => c.Country == "India" && c.Status == "A");
    
                if (results.Any()) {
                    Console.WriteLine(results.First().Country);
                }
    
                Console.ReadLine();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2017-07-16
      • 2016-04-24
      • 1970-01-01
      • 2012-09-23
      相关资源
      最近更新 更多