编辑嵌套列表中的元素
本文关键字:元素 列表 嵌套 编辑 | 更新日期: 2023-09-27 18:01:48
我有一个嵌套的列表元素。我需要修改列表中的一个特定元素
public List<List<string>> index = new List<List<string>>();
我需要从这个列表中改变值。在其中搜索一个特定的单词,如果它有,我需要得到索引,然后改变值。
遍历主列表,然后搜索要更改的单词的索引,如果找到,则更改并停止迭代
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;
}
}
或者,如果您计划使用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;
}