2015-11-04 97 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塊的順序。