[英]Changing List values dynamically in C#
I have the following problem: I have List of strings. 我有以下问题:我有字符串列表。 I also have a class with a string property called Name, and a constructor for the class that takes a string as its one argument.
我还有一个带有名为Name的字符串属性的类,以及一个将字符串作为其一个参数的类的构造函数。 So, I can create a List of objects by iterating over the List of strings.
因此,我可以通过遍历字符串列表来创建对象列表。
Now, I'd like to change the Name property of one of these objects, and as a result update the original List of strings automagically. 现在,我想更改这些对象之一的Name属性,并因此自动更新原始的字符串列表。 Is this possible?
这可能吗? I can't assume that the List of strings have unique values.
我不能假设字符串列表具有唯一值。 Here's some basic code that does not solve my problem, but hopefully illustrates what I need to do:
这是一些不能解决我的问题的基本代码,但希望能说明我需要做的事情:
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;
}
}
}
Can anyone suggest the best approach to this problem? 谁能建议解决此问题的最佳方法?
If you're willing to change nameList
to be of type List<Func<string>>
then you could do this: 如果您愿意将
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());
}
That outputs: 输出:
Andy
Betty
Charlie
Betty
You are updating person instance from personList
and printing nameList
at the end. 您正在从
personList
更新人员实例并在最后打印nameList
。 I guess you need to swap the order of foreach
blocks. 我想您需要交换
foreach
块的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.