C # Multiple Comparator implementations

Source: Internet
Author: User

C # Collection Implementation of the de-weight, intersection, difference set, etc., used to compare, there are several ways to meet.

Data:

varList =NewList<myclass> {    NewMyClass {MyProperty1 ="Ten", MyProperty2 =" -" },    NewMyClass {MyProperty1 ="Ten", MyProperty2 =" -" },    NewMyClass {MyProperty1 =" -", MyProperty2 =" -" }};

Method One:

 Public classmyclass{ Public stringMyProperty1 {Get;Set; }  Public stringMyProperty2 {Get;Set; }  Public Override BOOLEquals (Objectobj) {        if(ReferenceEquals (obj,NULL))return false; if(ReferenceEquals ( This, obj))return true; varo = obj asMyClass; returno.myproperty1.equals (o.myproperty1); }     Public Override intGetHashCode () {returnMyproperty1.gethashcode (); }}

Usage:

List. Distinct (); // Go heavy

Method Two:

 Public classMyclass:iequatable<myclass>{     Public stringMyProperty1 {Get;Set; }  Public stringMyProperty2 {Get;Set; }  Public BOOLEquals (MyClass other) {if(ReferenceEquals (Other,NULL))return false; if(ReferenceEquals ( This, other))return true; returnMyproperty1.equals (Other.    MYPROPERTY1); }}

Usage:

List. Distinct (); // Go heavy

Method Three:

 Public classmyclass{ Public stringMyProperty1 {Get;Set; }  Public stringMyProperty2 {Get;Set; }} Public classMyclassiequalitycomparer:iequalitycomparer<myclass>{     Public BOOLEquals (MyClass x, MyClass y) {if(ReferenceEquals (x,NULL))return false; if(ReferenceEquals (Y,NULL))return false; if(ReferenceEquals (x, y))return true; returnx.myproperty1.equals (y.myproperty1); }     Public intGetHashCode (MyClass obj) {returnobj.    Myproperty1.gethashcode (); }}

Usage:

List. Distinct (new myclassiequalitycomparer ()); // Go heavy

C # Multiple Comparator implementations

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.