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不存在于子列表中的客户?
var zipCodes = subList.Select( c=> c.ZipCode).Distinct().ToList();
var v = allCustomers.Where( c=> zipCodes.Contains(c.ZipCode) )
.Except(subList)
.ToList();
为什么你说V不应该包含邮政编码33333?allCustomers - subList将删除allCustomers的公共元素,但保留其唯一元素。
这是一个集合差,所以{a, B, C, D, E} - {a, B, C} = {D, E}因此33333应该显示…
与MSDN中的示例类似:http://msdn.microsoft.com/en-us/library/bb300779.aspx