2013-10-17 5 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

문제는 다른 지점에 있습니다

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 
} 
관련 문제