Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to determine if a value occurs more than x number of times

Tags:

c#

linq

I have a collection of objects which have a JobCode which is a string value. We have a business rule that says within the collection we should never have more than 4 elements who's JobCode is the same. I am struggling with this because usually I am comparing against some known value external to the list rather than comparing the list to itself.

Any help much appreciated.

like image 603
deanvmc Avatar asked Jan 22 '13 11:01

deanvmc


3 Answers

You can identify your bad jobs with:

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

It's not clear what remedial action you wish to take...

like image 118
spender Avatar answered Nov 02 '22 23:11

spender


You could group by your string property, then check if there is any group with more than 4 elements:

bool test = jobs.GroupBy(z => z.MyString).Any(z => z.Count() > 4);
like image 27
ken2k Avatar answered Nov 03 '22 00:11

ken2k


You would use GroupBy on the collection and than Count on the resulting groups:

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

The Key we select at the end is the property we used as a key in the GroupBy, i.e. it will contain the JobCode.

like image 7
Daniel Hilgarth Avatar answered Nov 02 '22 22:11

Daniel Hilgarth