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.
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...
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With