简体   繁体   中英

Removing duplicates from generic list

I defined an object, created an IEqualityComparer class for it, and used it like:

someList.Distinct(new DistinctComparer());

I thought this worked OK, but I was wrong. The comparer object specifies 11 properties of the object in the Equals method. I realized that the duplicates removed were random.

There is an additional property that I would like the removal based on, a Date. So for an object which had duplicates in the 11 properties, I would like to retain the object with the most recent date, the property of which is not included in the Equals method.

If it matters, the object is a US address as defined by the USPS. The Equals method:

      public bool Equals(Address x, Address y)
     {
        return x.HouseNo == y.HouseNo &&
           x.PreDir == y.PreDir &&
           x.StreetName == y.StreetName &&
           x.StreetSuffix == y.StreetSuffix &&
           x.PostDir == y.PostDir &&
           x.City  == y.City &&
           x.State == y.State &&
           x.Zip5 == y.Zip5 &&
           x.Zip4 == y.Zip4 &&
           x.Sud == y.Sud &&
           x.UnitNum == y.UnitNum;
     }

I do not know how to do have the address with the most recent sale date retained. Any clues? Thanks

So for an object which had duplicates in the 11 properties, I would like to retain the object with the most recent date, the property of which is not included in the Equals method.

In practice, Distinct will preserve (or rather, yield) the first of any equal values. So you can just order by date in reverse first:

var results = someList.OrderByDescending(x => x.Date)
                      .Distinct(new CustomComparerWhichIgnoresDate());

This behaviour is not guaranteed, but I'd be shocked to see it change - it's the simplest, most obvious approach. (See my Edulinq post on it for more details.) Whether or not you're happy to rely on that undocumented behaviour is up to you - there's a lot in LINQ to Objects which isn't documented, but which I'd be pretty confident about relying on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM