Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Distinct on list

Tags:

linq

distinct

I have a list like this:

List people

age   name
1     bob
1     sam
7     fred
7     tom
8     sally

I need to do a linq query on people and get an int of the number distinct ages (3)

int distinctAges = people.SomeLinq();

how? how?

like image 844
Ian Vink Avatar asked Dec 23 '22 03:12

Ian Vink


1 Answers

Select out the age, then use Distinct and Count.

 var ages = people.Select( p => p.Age ).Distinct().Count()

Or you could use GroupBy and Count

 var ages = people.GroupBy( p => p.Age ).Count();
like image 106
tvanfosson Avatar answered Jan 09 '23 21:01

tvanfosson