Vlad Vivdovitch
Vlad Vivdovitch

Reputation: 9815

Compare two objects on selected fields in C#

Code (that might potentially be pseudocode):

Person p1 = new Person { First = "John", Last = "Smith" };
Person p2 = new Person { First = "Jane", Last = "Smith" };

I'm looking for a way to do this:

bool b1 = Person.CompareOn({"First", "Last"}, p1, p2) // false;
bool b2 = Person.CompareOn({"Last"}         , p1, p2) // true;

Is there a predefined method that does this? Or do I have to write one myself?

Upvotes: 1

Views: 3148

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1503280

Do you have to specify the property names as strings rather than directly?

You could write your own custom IEqualityComparer<T> implementation which takes a projection - and then also give it an AndAlso method to take another projection. I have the first part in MiscUtil and the rest shouldn't be too hard to use.

You'd use it something like this:

// The first argument here is only for the sake of type inference
var comparer = PropertyEqualityComparer.WithExample(p1, p => p.First)
                                       .AndAlso(p => p.Last);
bool equal = comparer.Equals(p1, p2);

or:

var comparer = PropertyEqualityComparer<Person>.Create(p1, p => p.First)
                                               .AndAlso(p => p.Last);
bool equal = comparer.Equals(p1, p2);

Unfortunately you can't use params here as you may well want each projection to have a different target type.

(You'd want to create one comparer for each scenario if possible.)

Upvotes: 3

Gabriel
Gabriel

Reputation: 969

every class in C# derived from the main class: Object, and this have a method: equals(Object ), wich do the job. Is that method you should override

class Person {
     ...
     public bool Equals(Object o) {
          return (Person)o.LastName.Equals(this.LastName);
     }
 }

In the example, you should check if "o" is null or not, i'm checking for equals using lastname.

Upvotes: 0

Steve
Steve

Reputation: 2997

In the Person class :

public virtual bool Equals(Person obj){
        if (obj == null) return false;
        if (Equals(First, obj.First) == false) return false;
        if (Equals(Last, obj.Last) == false) return false;
        return true;
    }

Then you can say :

 if(person1.Equals(person2){
                    blah....
}

Upvotes: 0

Related Questions