Solved

How to change items in a list when iterating through the list.

Posted on 2013-06-08
6
389 Views
Last Modified: 2013-06-10
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;
            }
        }
0
Comment
Question by:brgdotnet
  • 3
  • 2
6 Comments
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 105 total points
ID: 39232462
That is exactly how you would do it, except that your collection variable is wrong. YOu wouldn't iterator over newPerson as that is not a collection--it's just one object. Instead you should be iterating over the Customers collection:

foreach(Person p in Customers)...

Open in new window


What you cannot do is this:

foreach(Person p in newPerson)
{
    p = new Person();
}

Open in new window


Attempting to modify the iterator variable itself will yield an exception. Modifying any properties of the object the iterator variable points to...that is OK.
0
 
LVL 62

Accepted Solution

by:
Fernando Soto earned 105 total points
ID: 39233024
Hi brgdotnet;

A couple of issues with the code you posted. You can not use the class Person as you have defined it. The form you chave used need ]s the backing store variables for each of the properties as shown below. You could allow the compiler to create these backing store variables on its own as follows the class Person which is commeted out. Inside the Form1 class you declared a List<Person> but that line of code does not allocate memory on the heap so you need to do that before you use it.

public class Person
{
    // Backing Store varible name added for Property Name
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    // Backing Store varible age added for Property Age
    private int age;
    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}

//public class Person
//{
//    public string Name { get; set; }
//    public int Age { get; set; }
//}

public partial class Form1 : Form
{

    List<Person> Customers;
    Person newPerson = new Person();


    public Form1()
    {
        InitializeComponent();

        // You need to allocate space on the heap for the Customers list
        Customers = new List<Person>();

        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);

        // You are iterating over the wrong object newPerson which is NOT a collection,
        // you would need to iterate over Customers but you can not modify the list in this
        // way.       
        // foreach(Person p in newPerson)
        // {
        //    p.Age=25;
        // }
        
        // So you can do the following in a single line of code.
        Customers.ForEach( c => c.Age = 25 );
    }
}

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39233036
@FernandoSoto
...you would need to iterate over Customers but you can not modify the list in this way.
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?
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39233052
@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.
0
 
LVL 2

Author Closing Comment

by:brgdotnet
ID: 39233792
Thank you Gentelmen, and God Bless you!
0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 39235596
Not a problem @brgdotnet, glad I was able to help and He has. ;=)
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question