2013-10-17 100 views
0

我需要从嵌套列表中添加值到特定列表。它会如果有任何列表包含一个名为inputString的值,如果是,则将结果添加到此列表中;如果不是,则用结果创建新的列表。代码如下。将值添加到嵌套列表中的特定列表C#

  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}); 

        } 
      } 
+4

那么,有什么问题呢? –

+1

'List.Add(result);'?? –

+1

只需调用'List.add(result)'? –

回答

4

的问题是在你的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 
}