[Solved] How to increase performance of foreach loop? [closed]


In case source as well as pList are long, you may try converting source into a Dictionary:

 // Provinding that all LongRecordId are distinct
 var dict = source
    .ToDictionary(item => item.LongRecordId, item => item);

 ...

 foreach (var item in pList) {
   MyRecord foundItem = null; //TODO: Put the right type here

   // Instead of O(N) - FirstOrDefault we have O(1) TryGetValue
   if (dict.TryGetValue(item.LongRecordId, out foundItem)) {
     foundItem.Readonly = pReadonly;
     selectionList.Add(foundItem);
   } 
 }

Edit: In case you want to ensure that selectionList contains distinct items only (see Ferhat Sayan’s comment) try HashSet

 ...

 HashSet<MyRecord> selectedHash = new HashSet<MyRecord>(selectionList);

 foreach (var item in pList) {
   MyRecord foundItem null; //TODO: Put the right type here

   // Instead of O(N) - FirstOrDefault we have O(1) TryGetValue
   if (dict.TryGetValue(item.LongRecordId, out foundItem)) {
     foundItem.Readonly = pReadonly;
     selectedHash.Add(foundItem);
   } 
 }

 selectionList = selectedHash.ToList();

3

solved How to increase performance of foreach loop? [closed]