我需要从嵌套列表中向特定列表添加值。如果有任何列表包含一个名为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});
}
}
答案 0 :(得分:4)
问题在于你的分支:
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
}