Change content in foreach

I tend to use ArrayLists of structures. It is then very easy to loop over the list using foreach.

I have a problem: I cannot use foreach to change the contents of structures and must use for types and messy types.

((dataStructure)files[x]).name = here;

      

Is there a neater way to do this?

+1


a source to share


4 answers


I know this sounds oversimplified, but it simply won't point to mutable value types .

They are almost never the right solution to a problem. There are very few exceptions, but classes are almost always appropriate.



Also, if you do use ArrayList

, then you will incur the cost of unboxing already ... (As Konrad says, if you can use .NET 2.0 then use generics.)

If you really insist on using mutable structures, use a loop for

instead foreach

. But please go for classes anyway.

+7


a source


Yes, there is: do not use untyped ArrayList

, these types are deprecated in favor of generic types in System.Collections.Generic

. In your case: List<T>

.



You still can't use it in conjunction with a loop foreach

to change the values ​​of a struct, but at least you don't need to cast.

+13


a source


Use a common version ArrayList

: List<DataStructure>

.

This way everything looks much better:

files[x].name = here;

      

+1


a source


Yes, there are times when it is List <T>

also not useful. In those cases, the oldest trick in the manual works. foreach

You should use a while loop instead :

while (listItem.Count >0)
{
//do operation with 0th element of List Item always like
 deletefunc(lisItem[0]);
}

      

0


a source







All Articles