Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make these foreach loops efficient?

Tags:

c#

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;
         }
     }
 }
like image 510
Rohit Raghuvansi Avatar asked Jan 21 '23 20:01

Rohit Raghuvansi


1 Answers

Here's one way,

    foreach (PatchFacilityManager PM in patchFacilityManager)
    {
        PM.IsSelected = facilityManagerId.Contains(PM.FacilityManagerId);
    }

EDIT

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.

like image 89
this. __curious_geek Avatar answered Jan 29 '23 20:01

this. __curious_geek