Linq Distinct listed

I have a list like this:

List of people

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

I need to make a linq request for people and get int numbers of different ages (3)

 int distinctAges = people.SomeLinq(); 

as? as?

+4
source share
2 answers

Choose an age, then use Distinct and Count.

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

Or you can use GroupBy and Count

  var ages = people.GroupBy( p => p.Age ).Count(); 
+11
source

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

You 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(); 
0
source

Source: https://habr.com/ru/post/1308510/


All Articles