簡體   English   中英

在C#中動態更改列表值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM