[英]C# Make List of dictionaries in List dynamically and populate/retrieve values
[英]Changing List values dynamically in C#
我有以下问题:我有字符串列表。 我还有一个带有名为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;
}
}
}
谁能建议解决此问题的最佳方法?
如果您愿意将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
您正在从personList
更新人员实例并在最后打印nameList
。 我想您需要交换foreach
块的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.