I have List of (PatchFacilityManager) and a List of (Int) facilityManagerId. I want to make the below code efficient. Is there any way to remove these two foreach loop.
foreach (PatchFacilityManager PM in patchFacilityManager)
{
foreach (int FM in facilityManagerId)
{
if (PM.FacilityManagerId == FM)
{
PM.IsSelected = true;
}
}
}
Here's one way,
foreach (PatchFacilityManager PM in patchFacilityManager)
{
PM.IsSelected = facilityManagerId.Contains(PM.FacilityManagerId);
}
This solution is efficient in two three ways IMHO as compared to the code given in the question.
First, it does not test for the condition and the result of the expression is straight away assigned into PM.IsSelected. As per LukeH's comment, it is mandatory to not set the PM.IsSelected to false, so the condition is unavoidable. However this improvement is applicable if the asked needs to set it to false. . From question asker's comment, his case seem to go right with this optimization. So no need for conditional assignment.
Second, it does not iterate through whole list, since List.Contains(int), returns true and come out of loop on the first occurrence of the int passed in argument.
Third, when framework gives you the functionality List.Contains(int), then why re-invent the wheel. So from maintenance perspective this is also more efficient.
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