How to modify the value of an object in a list using C#?

To modify the value of an object in a list, you can access the object by its index and modify its attribute value. Here is an example:

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个包含Person对象的List
        List<Person> persons = new List<Person>()
        {
            new Person() { Name = "Alice", Age = 25 },
            new Person() { Name = "Bob", Age = 30 },
            new Person() { Name = "Charlie", Age = 35 }
        };

        // 修改List中第一个Person对象的Name属性值
        persons[0].Name = "Alex";

        // 输出修改后的结果
        foreach (Person person in persons)
        {
            Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
        }
    }
}

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

Result of execution:

Name: Alex, Age: 25
Name: Bob, Age: 30
Name: Charlie, Age: 35

In the example above, we created a List containing three Person objects. Next, we accessed the first Person object by index and changed its Name property value to “Alex”. Finally, we looped through the entire List and outputted the properties of each Person object, confirming that the Name property of the first Person object was successfully modified.

bannerAds