C # Delete duplicate data in collections

Source: Internet
Author: User
  • List deduplication


Using the extension method system. LINQ. enumerable. Distinct ()

For a simple data type, you can simply call this function, because it uses the default comparator (system. Collections. Generic. equalitycomparer <t>. Default ).

Whether the default property check type T implements this system. iequatable <t> generic interface. If this attribute is implemented, an API containing iequatable <t> is returned. the implementation of the equals method is equalitycomparer <t>. Otherwise, it returns the equalitycomparer provided by T <t>.

For the class data type, you need to define an implementation class of the iequalitycomparer <t> interface, or directly implement system. iequatable <t> or iequalitycomparer <t> in the class.


Example 1:

private static List<EquityUniverse> DistinctEstimatesUniverse(List<EquityUniverse> universeList) {      return universeList.Distinct(new UniverseComparer()).ToList(); }
public class UniverseComparer : IEqualityComparer<EquityUniverse>    {        public bool Equals(EquityUniverse x, EquityUniverse y)        {            if (Object.ReferenceEquals(x, y)) return true;            return x.GlobalEntityId.Equals(y.GlobalEntityId) && x.CountryId.Equals(y.CountryId);        }        public int GetHashCode(EquityUniverse obj)        {            return obj.CountryId.GetHashCode() ^ obj.GlobalEntityId.GetHashCode();        }    }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.