greenoldman
greenoldman

Reputation: 21072

what is the pattern for modifying a collection in C#

What is the pattern (best practice) for such problem -- modifying elements (values) in collection?

Conditions:

In C++ it was easy and nice, I just iterated trough a collection and changed the elements. But in C# iterating (using enumerator) is read-only operation (speaking in terms of C++, only const_iterator is available).

So, how to do this in C#?

Example: having sequence of "1,2,3,4" modification is changing it to "1, 2, 8, 9" but not "1, 2, 3" or "1, 2, 3, 4, 5".

Upvotes: 1

Views: 349

Answers (2)

Brian Rasmussen
Brian Rasmussen

Reputation: 116421

Actually that depends. The readonly part applies to the iterator itself. If you're iterating a collection of objects, you can change the state of the objects via the reference.

For a collection of value types, you cannot change the elements during iteration, but in that case you can run through the elements using a regular loop and an indexer.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502186

Typically you'd go by index instead:

for (int i = 0; i < foo.Length; i++)
{
    if (ShouldChange(foo[i]))
    {
        foo[i] = GetNewValue(i);
    }
}

A more functional alternative is to create a method which returns a new collection which contains the desired "modified" data - it all depends on what you want to do though.

Upvotes: 5

Related Questions