2013-02-17 2 views
0

사전의 마지막 요소까지 조건을 검사해야하는 사전이 있습니다. 메서드 movenext를 사용했지만 예외를 던지고 있습니다. 배열 B의 요소가 올 때 수행하고 싶습니다. 각 요소를 비교합니다. A에서 마지막 원소까지 B보다 큽니다. 그런 다음 조건이 만족하는 키 값 쌍을 제거하십시오.반복의 반복

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Collections; 
using System.Diagnostics; 

namespace WellPuzzle 
{ 

    class Solution 
    { 
     public void falling_disks(int[] A, int[] B) 
     { 

      Dictionary<int, int> d1 = new Dictionary<int, int>(); 

      List<KeyValuePair<int, bool>> list = new List<KeyValuePair<int, bool>>(); 

      var enum1 = d1.GetEnumerator(); 
      int count = 0; 
      for (int i = 0; i <= A.Length - 1; i++) 
      { 
       //h1.Add(count++,A[i]); 
       d1.Add(count++, A[i]); 
      } 

      foreach (int ele in B) 
      { 

       foreach (KeyValuePair<int, int> item in d1) 
       { 
        var pair = item.Value; 

        if (ele <=pair && (enum1.MoveNext()!=null)) 
        { 
         continue; 
        } 
        else if (ele <= pair && (enum1.MoveNext() == null)) 
        { 

         list.Add(new KeyValuePair<int, bool>(pair, true)); 
         d1.Remove(pair); 
        } 
        else 
        { 
         //add key of current pair as filled in second hashtable 
         //remove element from first hashtable 
         //iterate till last 
         list.Add(new KeyValuePair<int, bool>(pair, true)); 
         d1.Remove(pair); 
        } 
} 
} 
} 
} 







    class Program 
    { 
     static void Main(string[] args) 
     { 
      int[] A = new int[] { 5, 6, 4, 3, 6, 2, 3 }; 
      int[] B = new int[] { 2 }; 
      Solution s1 = new Solution(); 
      s1.falling_disks(A, B); 
     } 
    } 
} 
+0

를 u는 다음 제거 새로운 컬렉션을 반복하여 제거하는 데 필요한 것들의 ID를 저장? –

+0

@Anonymiser : System.Linq을 "사용하고 있습니다". 물론 거기에는 이미 필요한 결과를 얻을 수있는 방법이 있습니다. 나는 당신이 원하는 정확한 결과를 이해하는 데 어려움을 겪고 있습니다. 입력 ('A'와'B')을 가정하고 출력 할 수 있습니까? –

+0

@syedmohsin, 분명히 "컬렉션 반복 중에 수정"- 예상대로. 질문이 없기 때문에 Anonymiser가이 예외를 원하거나 다른 일을해야하는지 여부는 불분명합니다. –

답변

2

열거 형을 반복하는 동안 수정할 수 없습니다. 이러한 상황에서

foreach(var item in someList) 
{ 
    if (someCondition) 
     someList.remove(item); // At run time you will get an exception saying that the collection was modified 
} 

에서와 같이 당신은 일반적으로 그것을 던지고 어떤 예외,

var itemsToRemove = new List<int>(); 
foreach(var item in someList) 
{ 
    if (someCondition) 
     itemsToRemove.Add(item.Id); 
} 

foreach(var id in itemsToRemove) 
{ 
    var item = someList.First(l => l.Id = id) 
    someList.Remove(item); 
} 
+0

하지만 @bassam .... 반복하면서 특정 조건에 대한 사전의 마지막 요소에 도달했는지 알고 싶었습니다. 사전에 대한 movenext 방법을 설명해 주시겠습니까? 아니면 마지막 요소에 도달 할 수있는 방법이 있는지? 조건을 만족하는 사전에 – Anonymiser

관련 문제