2012-10-11 37 views
-1

我的客户名单:和条件使用LINQ

List<customer> customerList; 

我希望得到的只是有国家=“印度”和状态=“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条件过滤对象。

任何人都可以告诉,有什么好方法,而不是调用condtion。

+1

您确定至少有一项满足这两个条件吗?您的第一个2个查询对我来说似乎是正确的... – digEmAll

+0

显示您的测试数据,因为2个linq语句在面值上看起来是正确的。 – BugFinder

+1

是“国家”和“状态”字符串变量,还是其他类型的变量? – Servy

回答

3

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

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

乔恩斯基特文章 - When should I use == and when should I use Equals?

对于值类型,我通常使用==更容易阅读的代码。东西 会变得棘手,如果一个值类型提供==的超负荷,其中 不同于等于,但我会认为这样的类型非常糟糕 设计开始。

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

0

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

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(); 
     } 
    } 
}