开发者

Compare lists and return objects that doesn't exist

开发者 https://www.devze.com 2023-03-01 02:54 出处:网络
class Customer : IEquatable<Customer> { public string FirstName { get; set; } public string LastName { get; set; }
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 is not supposed to return customer with zipcode "33333". How do i compare so that it ignores those Customers whose Zip is not present in the Sublist?


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


Why are you saying V should not include zipcode 33333? allCustomers - subList would remove the common elements but keep the unique elements of allCustomers.

It's a set difference, so {A, B, C, D, E} - {A, B, C} = {D, E} thus the 33333 should show...

Seems similar to this example from MSDN: http://msdn.microsoft.com/en-us/library/bb300779.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消