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 do开发者_如何学Pythones this? Or do I have to write one myself?
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.)
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....
}
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.
精彩评论