Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if properties across objects in a list are equal?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading