Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if property value of each list member is same

Tags:

c#

linq

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?

like image 249
user1151923 Avatar asked Aug 28 '13 11:08

user1151923


2 Answers

You can check by using All method, presumably your list have students:

var firstStudent = students.First();
students.All(s => s.Age == firstStudent.Age);
like image 163
cuongle Avatar answered Oct 19 '22 18:10

cuongle


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.)

like image 44
Rawling Avatar answered Oct 19 '22 18:10

Rawling