Convert Linq query expression to exact notation

I'm just starting to learn LINQ. I wrote the following linq expression to get numbers in a list that are repeated 3 times.

var query = from i in tempList where tempList.Count(num => num == i) == 3 select i; 

I want to know how to convert this to dot notation.

+4
source share
2 answers

You can use Enumerable.GroupBy :

 var query = tempList .GroupBy(i => i) .Where(g => g.Count() == 3) .Select(g => g.Key); 

For instance:

 var tempList = new List<Int32>(){ 1,2,3,2,2,2,3,3,4,5,6,7,7,7,8,9 }; IEnumerable<int> result = tempList .GroupBy(i => i) .Where(g => g.Count() == 3) .Select(g => g.Key); Console.WriteLine(string.Join(",",result)); 

Result: 3.7

+5
source

A literal conversion is as follows:

 var query = tempList.Where(i => tempList.Count(num => num == i) == 3); 

As Tim already mentioned, you can also achieve this with GroupBy:

 var query = tempList.GroupBy(i => i).Where(g => g.Count() == 3).Select(g => g.Key); 

Note that the GroupBy version GroupBy returns one copy of each number, unlike your code, which returns three copies of each number. Although I suspect that you would prefer to get only one copy of each number.

+1
source

All Articles