编辑嵌套列表中的元素

问题描述 投票:0回答:2

我有一个嵌套的列表元素。我需要改变该列表中的一个特定元素。

public List<List<string>> index = new List<List<string>>();

从该列表中,我需要改变值。搜索其中的一个特定单词,如果它有,我需要得到索引,然后改变值。

c# list nested-lists
2个回答
3
投票

迭代主列表,然后搜索你想改变的单词的索引,如果找到了,就改变它,然后停止迭代。

List<List<string>> index = new List<List<string>>();
foreach (List<string> list in index)
{
    int i = list.IndexOf("word to search");
    if (i >= 0) {
        list[i] = "new word";
        break;
    }
}

1
投票

或者,如果你打算使用Linq,你可以使用一个叫做 选择器,同时也获得源元素的索引。.

    static bool SearchAndReplace (List<string> strings, string valueToSearch, string newValue)
    {
        var found = strings.Select ((s,i)=> new{index=i, val=s}).FirstOrDefault(x=>x.val==valueToSearch);
        if (found != null)
        {
            strings [found.index] = newValue;
            return true;
        }
        return false;
    }

    static bool SearchAndReplace (List<List<string>> stringsList, string valueToSearch, string newValue)
    {
        foreach (var strings in stringsList)
        {
            if (SearchAndReplace(strings, valueToSearch, newValue))
                return true;
        }
        return false;

    }
© www.soinside.com 2019 - 2024. All rights reserved.