I have the following foreach loop:
List<WorkingJournal> workingJournals = new List<WorkingJournal>();
foreach (WorkRoster workRoster in workRosters)
{
bool exists = workingJournals.Any(workingJournal => workingJournal.ServicePlan.Id == workRoster.ServicePlan.Id
&& workingJournal.Nurse.Id == workRoster.Nurse.Id
&& workingJournal.Month == workRoster.Start.Month
&& workingJournal.Year == workRoster.Start.Year);
if (exists == false)
{
WorkingJournal workingJournal = new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
};
workingJournals.Add(workingJournal);
}
}
I started writing:
from workRoster in workRosters
select new WorkingJournal
{
ServicePlan = workRoster.ServicePlan,
Nurse = workRoster.Nurse,
Month = workRoster.Start.Month,
Year = workRoster.Start.Year
};
But now I am stuck with the comparison that produces distinct WorkingJournals.
I have a feeling that a group by clause should be here but I’m not sure how it should be done.
If you have proper
EqualsandGetHashCodeimplementations inside your class, you can simply invokeDistinct().On the chance you do not have such implementations, you can define an
IEqualityComparer<WorkingJournal>implementation. This will have you definingEqualsandGetHashCodemethods for theTthat can then be used by a dictionary or hashset and can also be used in overloads ofDistinct()in Linq.