1

I have these two objects (dummy code)

var students = new List<Student>();  
var girl = new Student() { Name = "Simran", StudentId = 4 };  
var sameGirl = new Student() { Name = "Norman", StudentId = 4 };

I wanted to check if these two objects are the same using the Intersect method but to my understanding Intersect uses Equals under the hood so these two objects will evaluate to false, I don't really know how to override the Equals or Intersect methods, but in essence, I want to check if the Ids of the objects are the same. Can the Equals or Intersect method be overridden to evaluate a part of the object, not the whole object?

Asker
  • 97
  • 1
  • 11
  • 1
    Does this answer your question? [How to best implement Equals for custom types?](https://stackoverflow.com/questions/567642/how-to-best-implement-equals-for-custom-types) – Pavel Anikhouski Mar 17 '20 at 19:59
  • 2
    Do you mean Intersect instead of Intercept? – juharr Mar 17 '20 at 20:01
  • 1
    i meant intersect my apologies – Asker Mar 17 '20 at 20:04
  • Note that `Enumerable.Intersect` has an overload that takes an `IEqualityComparer` so you could pass that to override just the calls to `Intersect`. You can not use `Intersect` with EF Core - why did you tag with that? – NetMage Mar 17 '20 at 21:50

2 Answers2

3

It depends upon your choice. You can override the Equals method and just compare only required properties and on the basis of comparison, return true or false.

So, implement IComparer and override the Equals method. Only include StudentId of the source and target for comparison. Would that fulfill your requirement?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Usman
  • 2,742
  • 4
  • 44
  • 82
  • 4
    Note, if you override `Equals` you should also override `GetHashCode`. – juharr Mar 17 '20 at 20:15
  • Exactly this method is very important. GetHashCode will confirm that it includes only the specified properties for comparison. – Usman Mar 18 '20 at 10:19
0
thank you all for your help, you pointed me out in the right direction, I didn't really understand how to override the equals or the comparer

   public class fooComparer<T> : IEqualityCmparer<T> where T :notnull
    {
    public book Equals(T? x, T? y)
    {
    return x?.studentId == y?.studentId && x!= null
    }
    public int GetHashCode(T obj)
    {
    return $"{obj.StudentId}
    _{obj.Name}".GetHashCode():}}
    }
Asker
  • 97
  • 1
  • 11