====== Remove an item from a dictionary ====== using System.Collections.Generic using System.Data using System.Linq function Start( ) as void local oDict as Dictionary local nItem as int local nItems as int local aRemove as int[] local nLength as int local oRemove as List local nChoice as int nChoice := 5 // change to test different possibilities nItems := 10000 System.Console.WriteLine( i"Building the dictionary with {nItems} items" ) oDict := Dictionary{} for nItem := 0 upto 10000 oDict:Add( nItem:ToString(), nItem ) next System.Console.WriteLine( "Removing items from dictionary" ) aRemove := { 567, 235, 1, 7435, 8835, 96276, 234, 567 } oRemove := List{} foreach nValue as int in aRemove System.Console.WriteLine( i"removing {nValue} from dictionary" ) switch nChoice case 1 // runtime error. A collection cannot be changed during the iteration foreach oItem as KeyValuePair in oDict if oItem:Value == nValue oDict:Remove( oItem:Key ) nLength := oDict:Count System.Console.WriteLine( i"removed {nValue} from dictionary, has a remainder length of {nLength}" ) endif next case 2 // most primitive working, without LinQ foreach oItem as KeyValuePair in oDict if oItem:Value == nValue System.Console.WriteLine( String.Format( "adding key {0} to remove list", oItem:Key ) ) oRemove:Add( oItem:Key ) endif next foreach cKey as string in oRemove oDict:Remove( cKey ) nLength := oDict:Count System.Console.WriteLine( i"removed {cKey} from dictionary, has a remainder length of {nLength}" ) next oRemove:Clear() case 3 // runtime error, idea by Robert v.d.Hulst. A collection cannot be changed during the iteration var oItems := oDict:Where( {|Item| Item:Value == nValue } ) foreach var oItem in oItems oDict:Remove( oItem:Key ) System.Console.WriteLine( String.Format( "removed {0} from dictionary, has a remainder length of {1}", oItem:Key, oDict:Count ) ) next case 4 // uses LinQ, idea by Robert v.d.Hulst, my personal favorite foreach oItem as KeyValuePair in oDict:ToList() if oItem:Value == nValue oDict:Remove( oItem:Key ) System.Console.WriteLine( String.Format( "removed {0} from dictionary, has a remainder length of {1}", oItem:Key, oDict:Count ) ) endif next case 5 // uses LinQ - idea from Nick Friend, one liner oDict := oDict:Where( {|Item| Item:Value != nValue } ):ToDictionary( {|Item| Item:Key }, {|Item| Item:Value } ) System.Console.WriteLine( String.Format( "removed entries from dictionary, has a remainder length of {0}", oDict:Count ) ) end switch next System.Console.WriteLine("Finished") return