2011-04-25 40 views
2
class Customer : IEquatable<Customer> 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string ZipCode { get; set; } 

    public bool Equals(Customer other) 
    { 
     if (ReferenceEquals(null, other)) return false; 

     return this.FirstName.Equals(other.FirstName) && this.LastName.Equals(other.LastName) 
      && this.ZipCode.Equals(other.ZipCode); 
    } 

    public override bool Equals(object obj) 
    { 
     return this.Equals(obj as Customer); 
    } 

    public override int GetHashCode() 
    { 
     return this.FirstName.GetHashCode()^this.LastName.GetHashCode(); 
    } 
} 

static void Main(string[] args) 
{ 
    List<Customer> allCustomers = new List<Customer>(); 
    allCustomers.Add(new Customer { FirstName = "A", LastName = "V", ZipCode = "11111" }); 
    allCustomers.Add(new Customer { FirstName = "B", LastName = "W", ZipCode = "11111" }); 
    allCustomers.Add(new Customer { FirstName = "C", LastName = "X", ZipCode = "22222" }); 
    allCustomers.Add(new Customer { FirstName = "D", LastName = "Y", ZipCode = "33333" }); 
    allCustomers.Add(new Customer { FirstName = "E", LastName = "Z", ZipCode = "33333" }); 

    List<Customer> subList = new List<Customer>(); 
    subList.Add(new Customer { FirstName = "A", LastName = "V", ZipCode = "11111" }); 
    subList.Add(new Customer { FirstName = "B", LastName = "W", ZipCode = "11111" }); 
    subList.Add(new Customer { FirstName = "C", LastName = "X", ZipCode = "22222" }); 

    //This gives expected answer 
    var n = subList.Except(allCustomers).ToList(); 

    //This should compare only for those customers who zip matches with Sublist's zip 
    //This returns customers with zip code "33333" while it should not 
    var v = allCustomers.Except(subList).ToList(); 
} 

var V不應該返回郵政編碼爲「33333」的客戶。我如何進行比較,以便忽略Zip列表中不存在的那些客戶?不存在的比較列表和返回對象

+0

這將是LINQ加入的經典案例。我碰巧不喜歡Linq Joins的語法,這導致我不能從內存中得出答案:) – sehe 2011-04-25 19:35:30

+0

另外,我認爲如果哈希碼包含郵政編碼會更好;另請參閱http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode有關實施GetHashCode的一般建議 – sehe 2011-04-25 19:41:04

+0

這似乎對我工作正常。 {A,B,C,D,E} - {A,B,C} = {D,E} ...我錯過了什麼嗎? – 2011-04-25 19:41:38

回答

4
var zipCodes = subList.Select(c=> c.ZipCode).Distinct().ToList(); 
var v = allCustomers.Where(c=> zipCodes.Contains(c.ZipCode)) 
        .Except(subList) 
        .ToList(); 
0

你爲什麼說V不應該包含郵編33333? allCustomers - subList將刪除共同元素,但保留所有客戶的獨特元素。

這是一組差,所以{A,B,C,d,E} - {A,B,C} = {d,E}因此33333應顯示...

似乎類似於這個例子來自MSDN:http://msdn.microsoft.com/en-us/library/bb300779.aspx

+0

好吧,所以我猜這不是一個問題,除了如何獲得用戶想要的元素。我的回答更多地提到「var v不應該帶着33333 zip返回客戶」,就好像除了不能正常工作。現在回想起來,這是一個什麼查詢會給他想要的東西的問題。 – 2011-04-25 19:47:21