简体   繁体   中英

StringCollection.Count incrementing unexpectedly

I'm working on a method that will trim each element in a StringCollection to remove all the excess in each element that I don't need. What is strange is when I was trying to get this method working (it does now) I noticed when introducing a breakpoint in the code that the groupsToClean.Count gets incremented with each iteration of the for loop and I can't see why.

Does anyone know why?

private StringCollection CleanUpGroups(StringCollection groupsToClean)
{
    StringCollection cleanedGroups = groupsToClean;

    for (int i = 0; i < groupsToClean.Count; i++)
    {
        if (groupsToClean[i].IndexOf(",") != -1)
        {
            string temp = groupsToClean[i].Substring(3, (groupsToClean[i].IndexOf(",") - 3));
            cleanedGroups.Add(temp);
        }
        else
            break;
    }

    return cleanedGroups;
}

Thanks for any insight!

Because StringCollection is a reference type. Your cleanedGroups and groupsToClean are the same object, so you add "cleaned" items to the collection from which you originally got them.

To solve this problem just create new cleanedGroups at the beginning of your method:

private StringCollection CleanUpGroups(StringCollection groupsToClean)
{
    var cleanedGroups = new StringCollection();

This line creates two references to the same collection:

StringCollection cleanedGroups = groupsToClean;

So when you call this, you're actually adding to the groupsToClean collection too:

cleanedGroups.Add(temp);  // adds to groupsToClean too

You'll need to replace the original occurrence with your modified one, or create a new collection.

StringCollection is a reference type. cleanedGroups is not a copy of groupsToClean -- it's the same instance.

You can convert the StringCollection to an Array to clone it

look at the MS reference: https://msdn.microsoft.com/en-us/library/system.collections.specialized.stringcollection.copyto(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM