C# 在C中动态更改列表值#
我有以下问题:我有字符串列表。我还有一个名为Name的字符串属性类,以及一个将字符串作为其一个参数的类的构造函数。因此,我可以通过迭代字符串列表来创建对象列表 现在,我想更改其中一个对象的Name属性,并自动更新原始字符串列表。这可能吗?我不能假设字符串列表具有唯一的值。下面的一些基本代码并不能解决我的问题,但希望能说明我需要做什么:C# 在C中动态更改列表值#,c#,list,updates,C#,List,Updates,我有以下问题:我有字符串列表。我还有一个名为Name的字符串属性类,以及一个将字符串作为其一个参数的类的构造函数。因此,我可以通过迭代字符串列表来创建对象列表 现在,我想更改其中一个对象的Name属性,并自动更新原始字符串列表。这可能吗?我不能假设字符串列表具有唯一的值。下面的一些基本代码并不能解决我的问题,但希望能说明我需要做什么: using System; using System.Collections.Generic; using System.Linq; public class
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;
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
公共课程
{
公共静态void Main()
{
列表名称列表=新列表(新字符串[]{“Andy”,“Betty”});
List personList=新列表();
foreach(名称列表中的字符串名称)
{
Person newPerson=新人(姓名);
personList.Add(newPerson);
}
foreach(个人列表中的个人)
{
Console.WriteLine(person.Name);
}
/*注意:下面两行仅用于说明
更改某人的姓名属性。*/
Person-aPerson=personList.First(p=>p.Name==“Andy”);
aPerson.Name=“查理”;
foreach(名称列表中的字符串名称)
{
Console.WriteLine(名称);
}
/*其输出为:
安迪
贝蒂
安迪
贝蒂
但我想得到:
查理
贝蒂
安迪
贝蒂
}
公共阶层人士
{
公共字符串名称;
公众人物(字符串名称)
{
名称=名称;
}
}
}
有人能提出解决此问题的最佳方法吗?如果您愿意将
名称列表
更改为列表
类型,则可以执行以下操作:
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());
}
您正在从
个人列表
更新个人实例,并在末尾打印姓名列表
。我想您需要交换每个块的顺序。当您可以迭代列表
以获取最新名称时,您是否需要更新原始列表?您的意思是输出应该是Charlie Betty Andy Betty这很奇怪,代码应该可以工作。我做了错误的编辑。我的错@KevinAvignon预期的输出是正确的,但不是代码。见下面我的答案。
Andy
Betty
Charlie
Betty