brgdotnet
asked on
How to change items in a list when iterating through the list.
How can I iterate through a C# list, and change the values in the list. Below is some code to refer to. Basically in this example I want to change everyones age to 25.
public class Person
{
public string Name
{
get { return Name; }
set { Name = value; }
}
public int Age
{
get { return Age; }
set { Age = value; }
}
}
public partial class Form1 : Form
{
List<Person> Customers;
Person newPerson = new Person();
public Form1()
{
InitializeComponent();
newPerson.Name = "Bob";
newPerson.Age = 30;
Customers.Add(newPerson);
newPerson.Name = "Mickey";
newPerson.Age = 29;
Customers.Add(newPerson);
newPerson.Name = "Jan";
newPerson.Age = 29;
Customers.Add(newPerson);
foreach(Person p in newPerson)
{
p.Age=25;
}
}
public class Person
{
public string Name
{
get { return Name; }
set { Name = value; }
}
public int Age
{
get { return Age; }
set { Age = value; }
}
}
public partial class Form1 : Form
{
List<Person> Customers;
Person newPerson = new Person();
public Form1()
{
InitializeComponent();
newPerson.Name = "Bob";
newPerson.Age = 30;
Customers.Add(newPerson);
newPerson.Name = "Mickey";
newPerson.Age = 29;
Customers.Add(newPerson);
newPerson.Name = "Jan";
newPerson.Age = 29;
Customers.Add(newPerson);
foreach(Person p in newPerson)
{
p.Age=25;
}
}
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@kaufmed;
I am in agreement with your statement in the your post. What I was trying to state to brgdotnet is that his foreach loop was trying to iterate over a single object and NOT a collection as is needed, a collection as Customers, but what he wanted to do can not be done. Sorry if it confused anyone.
I am in agreement with your statement in the your post. What I was trying to state to brgdotnet is that his foreach loop was trying to iterate over a single object and NOT a collection as is needed, a collection as Customers, but what he wanted to do can not be done. Sorry if it confused anyone.
ASKER
Thank you Gentelmen, and God Bless you!
Not a problem @brgdotnet, glad I was able to help and He has. ;=)
You most certainly can modify the age within a foreach loop. That's exactly what you're one-liner is doing ; )
Or am I misunderstanding what you were saying in that line?