Changing an element in foreach through the mode

Start with the following snippet:

Foreach(Record item in RecordList){
  ..
  item = UpdateRecord(item, 5);
  ..
}

      

The UpdateRecode function modifies some field of an element and returns the modified object. In this case, the compiler will throw an exception saying that the item cannot be updated in the foreach iteration.

Now the UpdateRecord method is changed so that it returns void and the fragment will look like this:

Foreach(Record item in RecordList){
  ..
  UpdateRecord(item, 5);
  ..
}

      

In this case, the item will be updated because the record is a reference type. But this makes the code unreadable.

The project I am working on has many foreach loops with almost the same code over and over, so I would like to create methods that update parts of the records. Is there a good way to do this? One that makes the code more readable instead of tracing it even further?

+1


source to share


3 answers


If you need to update a collection, don't use the iterator pattern as you said its error prone or smells bad.



I find that using a for loop with an index in this situation is a little clearer as it is very obvious what you are trying to do this way.

+1


source


The compiler complains that you cannot update the collection, not the entry. By doing item = UpdateRecord, you are reassigning the item to the iterator variable.

I disagree that UpdateRecord (item, 5) is not readable in any way, but if you feel better the extension method might make it clearer that you are changing the content of the item.



static void Update(this Record item, int value) {
   // do logic
}

foreach (Record item in RecordList) {
   item.Update(5);
}

      

+1


source


Do you need to update the same list? Could you return a new (updated) enum?

foreach(Record item in RecordList){
  ..
  yield return GetUpdatedRecord(item, 5);
  ..
}

      

0


source







All Articles