kr13
kr13

Reputation: 537

Converting Linq query expression to dot notation

I am 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.

Upvotes: 4

Views: 1221

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460268

You could use Enumerable.GroupBy:

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

For example:

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

Upvotes: 5

Mark Byers
Mark Byers

Reputation: 839054

A literal conversion is as follows:

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

As Tim already mentioned, you could also achieve this using a GroupBy:

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

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

Upvotes: 1

Related Questions