why isn't my lock working

hey all, hope ya’ll r well
today ihave been looking through documentation and others answers but i cant make to seem any sence out if them or well not a case specific answer but what i have come up with is for my foreach loop is placing a lock on it so i can remove items so far i have come up with this for my dictionary removal but i am getting an error and from what i am understanding after reading alot of peoples questions and solutions that i am placing the lock in there correctly but… Aparently not

    public void Remove()
      {
         List<SelectedInfo> selectedObjects = playerController.GetSelected();
         
         foreach (SelectedInfo unit in selectedObjects)
         {
            if (unit.isSelected)
            {
               lock (groupLookupCache)
               {
                  foreach (var item in groupLookupCache)
                  {
                     for (int i = 0; i < item.Key.Length; i++)
                     {
                        this.groupLookupCache.Remove(item.Key);
                     }
                  }
               }
            }
         }
      }

this is the error i am reciving
InvalidOperationException: Collection was modified; enumeration operation may not execute.
System.Collections.Generic.Dictionary`2+Enumerator[TKey,TValue].MoveNext () (at <437ba245d8404784b9fbab9b439ac908>:0)
RPG.Inventories.UnitSelectionGroup.Remove () (at Assets/Scripts/Inventories/UnitSelectionGroup.cs:95)
RPG.Inventories.UnitSelectionGroup.Update () (at Assets/Scripts/Inventories/UnitSelectionGroup.cs:42)

would someone be able to point me in the right direction maybe some good videos of locks or removal of keys while itereating

any help would be appreciated i am making a case specific question because im having trouble understanding some of the finer details that others are talking about (my key is also a component)

Hello again. Foreach loop is not going to be able to continue it’s work when it’s modified, meaning that something has been removed, added, etc. I recommend you instantiate an identical dictionary and manipulate that and then apply the changes to the actual dictionary of your preference. So:

      foreach (SelectedInfo unit in selectedObjects)
      {
         if (unit.isSelected)
         {
                var tc = new Dictionary<YOURDATATYPE, YOURDATATYPE>(groupLookupCache);
                for (i = 0; i < tc.Count; i++)
                {
                         for (j = 0; j < tc*.Key.Length; j++)*

{
groupLookupCache.Remove(item.Key);
}
}
}
}
You could also go with a foreach loop.