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.
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 ...
You would use GroupByin a collection and Countfor result groups:
GroupBy
Count
var jobCodesWithMoreThanFourOccurences = collection.GroupBy(x => x.JobCode) .Where(x => x.Count() > 4) .Select(x => x.Key);
Key, , , GroupBy, JobCode.
Key
JobCode
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);