2015-11-04 72 views
1

我有以下问题:我有字符串列表。我也有一个名为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; 
     } 
    } 
} 

任何人都可以提出解决这个问题的最好方法?

+3

当您只需迭代'List '获取最新名称时,您是否需要更新原始列表? – Steve

+1

你的意思是输出应该是查理贝蒂安迪贝蒂 –

+0

这很奇怪,但代码应该工作。 –

回答

1

如果你愿意改变nameListList<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

您从personList更新人员实例和打印nameList最后。我想你需要交换foreach块的顺序。