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.
>Solution :
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);