我有一个嵌套的列表元素。我需要改变该列表中的一个特定元素。
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;
}