在C#中动态更改列表值

时间:2015-11-04 03:08:35

标签: c# list updates

我有以下问题:我有字符串列表。我还有一个带有名为Name的字符串属性的类,以及一个以字符串作为其一个参数的类的构造函数。因此,我可以通过迭代字符串列表来创建对象列表。

现在,我想更改其中一个对象的Name属性,结果会自动更新原始的字符串列表。这可能吗?我不能假设字符串列表具有唯一值。这里有一些基本代码无法解决我的问题,但希望说明我需要做的事情:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        List<string> nameList = new List<string>(new string[] {"Andy", "Betty"});
        List<Person> personList = new List<Person>();
        foreach (string name in nameList)
        {
            Person newPerson = new Person(name);
            personList.Add(newPerson);
        }

        foreach (Person person in personList)
        {
            Console.WriteLine(person.Name);
        }

        /* Note: these next two line are just being used to illustrate
        changing a Person's Name property. */ 
        Person aPerson = personList.First(p => p.Name == "Andy");
        aPerson.Name = "Charlie";

        foreach (string name in nameList)
        {
            Console.WriteLine(name);
        }

        /* The output of this is:
        Andy
        Betty
        Andy
        Betty

        but I would like to get:
        Charlie
        Betty
        Andy
        Betty
    }

    public class Person
    {
        public string Name;

        public Person(string name)
        {
            Name = name;
        }
    }
}

有人能建议解决这个问题的最佳方法吗?

2 个答案:

答案 0 :(得分:1)

如果您愿意将nameList更改为List<Func<string>>类型,那么您可以这样做:

List<Person> personList =
    new string[] { "Andy", "Betty" }
        .Select(n => new Person(n))
        .ToList();

foreach (Person person in personList)
{
    Console.WriteLine(person.Name);
}

Person aPerson = personList.First(p => p.Name == "Andy");
aPerson.Name = "Charlie";

List<Func<string>> nameList =
    personList
        .Select(p => (Func<string>)(() => p.Name))
        .ToList();

foreach (Func<string> f in nameList)
{
    Console.WriteLine(f());
}

输出:

Andy
Betty
Charlie
Betty

答案 1 :(得分:1)

您正在从personList更新人员实例,并在结尾处打印nameList。我想你需要交换foreach块的顺序。