向嵌套列表 C# 中的特定列表添加值
本文关键字:列表 添加 嵌套 | 更新日期: 2023-09-27 18:35:57
我需要从嵌套列表中向特定列表添加一个值。如果有任何列表包含一个名为 inputString 的值,如果是,则将结果添加到此列表中;如果否,则创建包含结果的新列表。代码如下。
foreach(List<string> List in returnList )
{
if (List.Contains(inputString))
{
//add a string called 'result' to this List
}
else
{
returnList.Add(new List<string> {result});
}
}
问题出在您的 else 分支中:
foreach (List<string> List in returnList)
{
if (List.Contains(inputString))
{
//add a string called 'result' to this List
List.Add(result); // no problem here
}
else
{
// but this blows up the foreach
returnList.Add(new List<string> { result });
}
}
解决方案并不难,
// make a copy with ToList() for the foreach()
foreach (List<string> List in returnList.ToList())
{
// everything the same
}