简体   繁体   中英

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. 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. 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:

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. I guess you need to swap the order of foreach blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM