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列表中不存在的那些客戶?不存在的比較列表和返回對象
這將是LINQ加入的經典案例。我碰巧不喜歡Linq Joins的語法,這導致我不能從內存中得出答案:) – sehe 2011-04-25 19:35:30
另外,我認爲如果哈希碼包含郵政編碼會更好;另請參閱http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode有關實施GetHashCode的一般建議 – sehe 2011-04-25 19:41:04
這似乎對我工作正常。 {A,B,C,D,E} - {A,B,C} = {D,E} ...我錯過了什麼嗎? – 2011-04-25 19:41:38