Linq to determine if a value occurs more than x times

I have a collection of objects that have a JobCode, which is a string value. We have a business rule that states that in a collection we should never have more than four elements that JobCode are the same. I struggle with this because I usually compare with some known value external to the list, rather than comparing the list with myself.

Any help is greatly appreciated.

+5
source share
3 answers

You can identify your bad assignments with:

Jobs.GroupBy(j => j.JobCode).Where(g => g.Count() > 4)

It is not clear what correction you want to take ...

+19
source

You would use GroupByin a collection and Countfor result groups:

var jobCodesWithMoreThanFourOccurences = collection.GroupBy(x => x.JobCode)
                                                   .Where(x => x.Count() > 4)
                                                   .Select(x => x.Key);

Key, , , GroupBy, JobCode.

+6

You can group your string property and then check if there is any group of more than 4 elements:

bool test = jobs.GroupBy(z => z.MyString).Any(z => z.Count() > 4);
+6
source

All Articles