So say I have a class Student with one property, int Age
. Now if I have List<Student> students
, how do I check if the age of all students in the list is equal?
You can check by using All
method, presumably your list have students:
var firstStudent = students.First();
students.All(s => s.Age == firstStudent.Age);
If you want to do this in one query, not two (which is generally bad practice),
bool allAgesAreTheSame = (students.Select(s => s.Age).Distinct().Count() < 2);
will do it for you.
This will also return true in the trivial case where you have no students at all, rather than throw an exception. (You could do == 1
rather than < 2
to return false in the trivial case instead.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With