I have two objects in a list and want to ensure that all properties of these objects are having the same value.
For example:
List<Person> persons = new List<Person>
{
new Person { Id = "1", Name = "peter" },
new Person { Id = "1", Name = "peter" }
};
Now I want to get true
as both objects properties are same. I have tried with the following lambda expression.
var areEqual = persons.All(o => o == persons.First());
but I'm getting false
in areEqual
. I'm unable to understand why this is so and want to know how to do it correctly.
CodePudding user response:
You can find out if all elements are the same by using:
persons.Distinct().Count() == 1
If it's zero there were no entries in the first place, if it's greater 1, you had entries that were not the same.
Now... how do you make sure the .Distinct()
call knows when two objects are the same?
Option 1:
Person
is already arecord
. Great. Inbuilt funtionality. Done.Option 2:
Person
implementsIEquatable<Person>
and it does the check you want.Option 3:
Person
overridesObject.Equals
andObject.GetHashCode
on it's own, in a way you need.Option 4:
Person
is neither of the above and you don't want to change it to check one of those boxes. Then you can still implement your ownIEqualityComparer<Person>
and pass an instance of it to the distinct method like this:persons.Distinct(new MyCustomPersonEqualityComparer()).Count() == 1
CodePudding user response:
This query would be meaningless if you have less than 2 items. So, take first element to compare to the rest
var allAreSame = persons
.All(p => p.Id == persons[0].Id && p.Name == persons[0].Name);
Or (faster way)
var allAreSame = !persons
.Any(p => p.Id != persons[0].Id || p.Name != persons[0].Name);
CodePudding user response:
Person
is a reference type, the default == is performing memory's location equality check. In order to perform your own equality check you must implement IComparable<Person>
.
You can also use record
instead of class
, this implements behind the hoods the equality checks on the record's public properties.
public record Person
{
public string Id { get; set; }
public string Name { get; set; }
}