我有以下问题:我有字符串列表。我也有一个名为Name的字符串属性的类,以及一个接受字符串作为其参数的类的构造函数。所以,我可以通过迭代字符串列表来创建一个对象列表。在C中动态更改列表值
现在,我想要更改其中一个对象的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;
}
}
}
任何人都可以提出解决这个问题的最好方法?
当您只需迭代'List'获取最新名称时,您是否需要更新原始列表? –
Steve
你的意思是输出应该是查理贝蒂安迪贝蒂 –
这很奇怪,但代码应该工作。 –