views:

73

answers:

2

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

Conditions:

  • size of the collection is not changed (no element is deleted or added)
  • modification is in-place

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".

+5  A: 

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.

Jon Skeet
So it seems here C++ is more flexible, thank you for the answer.
macias
+1  A: 

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.

Brian Rasmussen
Thank you. The first sentence is only partially true -- you don't know in advance if the element is immutable or not. In case of class the collection of it, is a collection of references -- this way you have to change the reference. And enumerator does not let you do this.
macias
@macias: The iteration variable is always read-only. However, if it is a reference, you can modify the instance it points to, but you cannot change the reference itself. Please see the link in my comment for your question.
Brian Rasmussen
I fully understand that -- my question is was how to it (the loop) look better. In C++ it is really nice, so it is surprising that in C# it looks ugly. That's all.
macias