Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2013-06-08
6
Medium Priority
?
396 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 420 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 64

Accepted Solution

by:
Fernando Soto earned 420 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 64

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 64

Expert Comment

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

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

721 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