比较列表并返回不存在的对象

时间:2011-04-25 19:31:53

标签: c# .net linq

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不在子列表中的客户?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

为什么你说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