2012-10-11 36 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(); 
     } 
    } 
}