About foreach

T

Tony Johansson

Hello!

In VS 2003 I almost certain that it wasn't possible to update a collection
with foreach because it was readonly.
Now in VS 2008 it seems to me that it possible to update by using foreach.

Below I have a collection named paramList that I first update by using a for
loop and that works fine.
Then I update by using a foreach and that too works just fine.

List<WorksheetRowParameter> paramList = MyParameterResult.Where(p =>
p.WorksheetRowID == wsrID).ToList();
for(int k = 0; k< paramList.Count(); k++)
paramList[k].WorksheetRowID = myPreviousWorksheetRowID;

foreach(WorksheetRowParameter wsrp in paramList)
wsrp.WorksheetRowID = myPreviousWorksheetRowID;

So just give me a comment about if it's poosible to use a foreach whan
update a collection

//Tony
 
A

Alberto Poblacion

Tony Johansson said:
foreach(WorksheetRowParameter wsrp in paramList)
wsrp.WorksheetRowID = myPreviousWorksheetRowID;

So just give me a comment about if it's poosible to use a foreach whan
update a collection

Observation: The above foreach only updates a property in the existing
elements of the collection, but it does not modify the collection itself.
Modifying the collection (adding or removing elements) is not allowed in a
foreach; changing the contents of an existing element in the colection IS
allowed. This has not changed since the earlier versions of .Net.
 
M

miher

Hi,

Actually You are not modifying the collection (=list of
WorksheetRowParameter references), but an item referenced by a reference in
the collection. So if You would try something like this :
foreach(WorksheetRowParameter wsrp in paramList)
paramList.Add(wsrp);
You should get Your exception.

Hope You find this useful.
-Zsolt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top