开发者

what is the pattern for modifying a collection in C#

开发者 https://www.devze.com 2022-12-22 14:16 出处:网络
What is the pattern (best practice) for such problem -- modifying elements (values) in collection? Conditions:

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 availab开发者_运维问答le).

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消