Solved

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

Posted on 2013-06-08
6
393 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

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…
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…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

623 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