views:

49

answers:

2

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?

+9  A: 

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();
tvanfosson
A: 

Download LinqPad and give these simple linq / lambda queries yourself. Its very easy to compare the SQL and equivalent Linq / lambda result set.

You would start with

select  Age, Name
from    People
group   by Age, Name

Then open another tab

var ages = (from    p in Peoples
group p by p.Age into g
select g);
ages.Dump();

Then open another tab

var ages = Peoples.GroupBy(p => p.Age);
ages.Dump();
Nicholas Murray