lamelemon lamelemon - 2 months ago 7
C# Question

Get a count of elements that appear once in a list with LINQ

Is it possible to get an integer count of elements that appear only once in a list with LINQ without creating a temporary list of those values and then counting that list?

Obviously this doesn't work but something like:

int test = list.Count(s => s.id).Where(s.id.Count() == 1);

Answer

You have to group them and the project the items which have count of 1 and then count the number of groups:

int test = list.GroupBy(s => s.id).
               .Where(g=> g.Count() == 1)
               .Count();