Comparing 2 list of objects in C# using IEquatable

preview_player
Показать описание
Comparing 2 list of objects in C# using IEquatable

To compare 2 list:

Class need to implement IEquatable interface, which provide implementation of Equals method. Below is link for example covered in video:
Рекомендации по теме
Комментарии
Автор

I have a question please, why do you get a warning to student Class?
I see if I don't use Iequitable and I override the Equals method this warning disappear. And my question is: is Equals being overriden inside student class?
I will leave bellow an example of this

public class Person //: IEquatable<Person>
{
public string Name { get; set; }
public int Age { get; set; }

//with override Equals it acts like IEquatable<Person> without the need to declare it.

public override bool Equals(object o)
{
if (o is Person student)
{
return (this.Name == student.Name && this.Age == student.Age);
}
return false;
}

//if I use : IEquatable<Person> I don't use override but I am getting warning
//user query Person defines operator == and != but doesn't override Equals (object o)
//however, it works!
//public bool Equals(Person other)
//{
// if (other is Person student)
// {
// return (this.Name == student.Name && this.Age == student.Age);
// }
// return false;
//}


public override int GetHashCode()
{
return this.Name.GetHashCode() ^ this.Age.GetHashCode();
}

public static bool operator ==(Person lhs, Person rhs)
{
if (lhs is null)
{
if (rhs is null)
{
return true;
}

return false;
}
return lhs.Equals(rhs);
}

public static bool operator !=(Person lhs, Person rhs)
{
if (lhs is null)
{
if (rhs is null)
{
return true;
}

return false;
}
return !lhs.Equals(rhs);
}


}

void Main()
{
var list3 = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 },
new Person { Name = "Charlie", Age = 35 },
new Person { Name = "Eve", Age = 50 }
};

var list4 = new List<Person>
{
new Person { Name = "Bob", Age = 30 },
new Person { Name = "David", Age = 35 },
new Person { Name = "Eve", Age = 50}//40 }
};

// you can use Console.WriteLine instead of Dump, Dump is at LINQ

list3.Dump("list3");
list4.Dump("list4");




}

mermaidoasis