简体   繁体   中英

C# linq Intersect override for complex object

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?

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?

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():}}
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM