Home > OS >  KeyedCollection Remove() issue
KeyedCollection Remove() issue

Time:01-10

I am trying to move items between two KeyedCollection:

KeyedCollection<string, Operation> Temporary;
Temporary = LoadedConfig;
foreach (var testOp in Temporary.ToList())
{
    if (!PerformTestOpListBox.Items.Contains(testOp.Name))
    {
        Temporary.Remove(testOp.Name);
    }
}
StagingConfig = Temporary;

By doing so it will supposed to remove the item in Temporary if the ListBox does not contain such item, but somehow I found out it will also removed the same item in LoadedConfig as well. How could that even happened? Is there a way to avoid it?

CodePudding user response:

So, your StagingConfig is null. Let's make a class that derives from KeyedCollection so you can set it to something that isn't null, then fill it:

public class OperationKeyedCollection : KeyedCollection<string, Operation>
{
    protected override string GetKeyForItem(Operation item) => item.Name;
}

Then you can make an instance:

StagingConfig = new OperationKeyedCollection();

And, let's worst case: you're iterating a million items in a config dictionary and only adding them if they're present in a list of 10 items. It's going to be better to just use the list of 10 as the driving source because the keyed collection can look up those list items in its dictionary really quickly. If we enumerate a million items, looking them up in a list of 10, most of them wont be there, a fact that we will determine after we check all 10 items. This means youre getting on for 10 million comparisons. Flip that over and use the list of 10 and you're asking a dictionary "do you have" just 10 times. A dictionary can answer that question after, probably just a single check, so you're doing more like 10 checks rather than 10 million

foreach (var opName PerformTestOpListBox.Items)
{
    if (LoadedConfig.TryGetValue(opName, out var op))
    {
        StagingConfig.Add(op);
    }
}
  •  Tags:  
  • Related