As HashSet<T>
provides unique items post filtering it. I wanted to use this with some given class objects but it didn't work however it is working with primitive types like int. My classes are now implementing IEqualityComparer.GetHashCode method is important here.
class Address : IEqualityComparer<Address>
{
public int PinCode { get; set; }
public string LocalAddress { get; set; }
public bool Equals(Address x, Address y)
{
if (x is null && y is null)
return true;
else if (x is null || y is null)
return false;
else if ((x.PinCode == y.PinCode) && (x.LocalAddress == y.LocalAddress))
return true;
else
return false;
}
public int GetHashCode(Address obj) =>
obj.LocalAddress.GetHashCode() * 17 + obj.PinCode.GetHashCode();
}
class Person : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x is null && y is null)
return true;
else if (x is null || y is null)
return false;
else if ((x.Name == y.Name) && (x.Address.LocalAddress == y.Address.LocalAddress) && (x.Address.PinCode == y.Address.PinCode))
return true;
else
return false;
}
public int GetHashCode(Person obj) =>
obj.Name.GetHashCode() * 17 + obj.Address.PinCode.GetHashCode() + obj.Address.LocalAddress.GetHashCode();
public string Name { get; set; }
public Address Address { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person
{
Name="Amar",
Address=new Address
{
PinCode=500018,
LocalAddress="Hyderabad"
}
},
new Person
{
Name="Amar",
Address=new Address
{
PinCode=500018,
LocalAddress="Hyderabad"
}
},
new Person
{
Name="Alok",
Address=new Address
{
PinCode=500018,
LocalAddress="Hyderabad"
}
}
};
HashSet<Person> uniquePeople = new HashSet<Person>(new Person());
uniquePeople.UnionWith(people);
Console.ReadLine();
}
Actual Result :- Count of this is coming as 2 Expected Result :- Count should be 2 }