Solved

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

Posted on 2013-06-08
6
384 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 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 105 total points
Comment Utility
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
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
@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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
@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
Comment Utility
Thank you Gentelmen, and God Bless you!
0
 
LVL 62

Expert Comment

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
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…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

762 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now