Solved

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

Posted on 2013-06-08
6
390 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 63

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
Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 63

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 63

Expert Comment

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

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

821 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