Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing objects value in foreach loop?

People also ask

How do I change the value of a forEach?

The following code will change the values you desire: var arr = ["one","two","three"]; arr. forEach(function(part, index) { arr[index] = "four"; }); alert(arr);

Can you change a forEach loop?

Why C#'s foreach loop cannot change what it loops over. With a foreach loop we easily iterate over all elements in a collection. During each pass through the loop, the loop variable is set to an element from a collection.

Can the elements of an array be updated using a forEach loop?

forEach does not modify the array itself, the callback method can. The method returns undefined and cannot be chained like some other array methods. forEach only works on arrays, which means you need to be a little creative if you want to iterate over objects.

Can we put condition in forEach?

No, a foreach simply works for each element.


You cannot change the iteration variable of a foreach-loop, but you can change members of the iteration variable. Therefore change the ChangeName method to

private void ChangeName(StudentDTO studentDTO)
{
    studentDTO.name = SomeName;
}

Note that studentDTO is a reference type. Therefore there is no need to return the changed student. What the ChangeName method gets, is not a copy of the student but a reference to the unique student object. The iteration variable and the studentDTOList both reference the same student object as does the studentDTO parameter of the method.

And change the loop to

foreach(StudentDTO student in studentDTOList)
{
    ChangeName(student);
}

However, methods like ChangeName are unusual. The way to go is to encapsulate the field in a property

private string name;
public string Name
{
    get { return name; }
    set { name = value; }
}

You can then change the loop to

foreach(StudentDTO student in studentDTOList)
{
    student.Name = SomeName;
}

EDIT

In a comment you say that you have to change many fields. In that case it would be okay to have a method UpdateStudent that would do all the changes; however I still would keep the properties.

If there is no additional logic in the properties besides passing through a value, you can replace them by the handy auto-implemented properties.

public string Name { get; set; }

In that case you would have to drop the field name.


You're not actually changing the object that you're referring to anyway, so you can just use:

foreach (StudentDTO student in studentDTOList)
{
    student.name = SomeName;
}

Or still call a method:

foreach (StudentDTO student in studentDTOList)
{
    ChangeStudent(student);
}

In both cases, the code doesn't change the value of the iteration variable (student) so it's okay.

But your original example doesn't compile anyway - an iteration variable introduced by a foreach loop is read-only.