Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向嵌套列表C中的特定列表添加值#_C#_Asp.net - Fatal编程技术网

C# 向嵌套列表C中的特定列表添加值#

C# 向嵌套列表C中的特定列表添加值#,c#,asp.net,C#,Asp.net,我需要从嵌套列表中向特定列表添加一个值。如果有任何列表包含一个名为inputString的值,它将显示,如果是,则将结果添加到此列表中;如果否,则创建带有结果的新列表。代码如下 foreach(List<string> List in returnList ) { if (List.Contains(inputString)) {

我需要从嵌套列表中向特定列表添加一个值。如果有任何列表包含一个名为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});

                    }
            }
foreach(返回列表中的列表)
{
if(List.Contains(inputString))
{
//将名为“result”的字符串添加到此列表
}
其他的
{
添加(新列表{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 });  
    }
}
foreach(返回列表中的列表)
{
if(List.Contains(inputString))
{
//将名为“result”的字符串添加到此列表
List.Add(result);//这里没问题
}
其他的
{
//但这会让foreach爆炸
添加(新列表{result});
}
}
解决办法并不难

// make a copy with ToList() for the foreach()
foreach (List<string> List in returnList.ToList())  
{
   // everything the same
}
//使用ToList()为foreach()创建副本
foreach(returnList.ToList()中的列表)
{
//一切都一样
}

问题出在您的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 });  
    }
}
foreach(返回列表中的列表)
{
if(List.Contains(inputString))
{
//将名为“result”的字符串添加到此列表
List.Add(result);//这里没问题
}
其他的
{
//但这会让foreach爆炸
添加(新列表{result});
}
}
解决办法并不难

// make a copy with ToList() for the foreach()
foreach (List<string> List in returnList.ToList())  
{
   // everything the same
}
//使用ToList()为foreach()创建副本
foreach(returnList.ToList()中的列表)
{
//一切都一样
}

那么问题出在哪里?
列表。添加(结果)?只需调用
List.add(结果)
?有什么问题吗?
List.add(结果)?只需调用
列表。添加(结果)