简体   繁体   English

从通用列表中删除重复项

[英]Removing duplicates from generic list

I defined an object, created an IEqualityComparer class for it, and used it like: 我定义了一个对象,为其创建了一个IEqualityComparer类,并按如下方式使用它:

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. 比较器对象在Equals方法中指定对象的11个属性。 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. 因此,对于在11个属性中具有重复项的对象,我想保留具有最新日期的对象,该对象的属性未包含在Equals方法中。

If it matters, the object is a US address as defined by the USPS. 如果重要,则对象是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. 因此,对于在11个属性中具有重复项的对象,我想保留具有最新日期的对象,该对象的属性未包含在Equals方法中。

In practice, Distinct will preserve (or rather, yield) the first of any equal values. 实际上, Distinct将保留(或更确切地说,屈服)任何相等值中的第一个 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. (有关更多详细信息,请参见我的Edulinq帖子 。)您是否愿意依靠未记录的行为取决于您-LINQ to Objects中有很多记录的东西,但是我会很高兴有信心依靠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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