2013-03-07 105 views
2

我正在試圖解決在http://users.metropolia.fi/~dangm/blog/?p=67上顯示的問題。 我是新來的c#語言。我想通過使用枚舉數的字典和特定條件迭代。所以有兩個變量current和previous.current指向dictionary.previous的第一個元素。previous指向previous中的元素。在迭代在字典我循環像FOLL迭代和修改字典

previous=current; 
current.MoveNext(); 

問題是,當我們反覆第一次直通整部字典之前的點最後一個元素的字典和當前點隨機密鑰值對RawVariable(0,0),但現在時我們通過詞典第二次迭代,我希望當前指向字典中的第一個元素。我是否使當前點指向某個具有特定鍵或值的元素

這是我的代碼片段

public void falling_disks(int[] A, int[] B) 
    { 
     Dictionary<int, int> filledDictionary = filldictionary(d1, A); 
     //previous stores the previous element in dictionary 
     var previous = filledDictionary .GetEnumerator(); 
     //current stores next element of previous 
     var current = filledDictionary .GetEnumerator(); 
     current.MoveNext(); 

     //for each incoming element in array B 
     foreach (int ele in B) 
     { 

      //check if the current key is filled in hashtable h1 that is check if it 
      //is already added 
      if (!checkifthatvalueisfilled(current.Current.Key)) 
      { 
       //if not check if current value is less than or equal to element 
       while ((current.Current.Value >= ele)) 
       { 
        //assign previous to current 
        previous = current; 
        //move current to next position 
        current.MoveNext(); 
       } 
       listofitemstoremove.Add(previous.Current.Key); 

      } 
      else 
      { 
       listofitemstoremove.Add(current.Current.Key); 
      } 

      foreach (int item in listofitemstoremove) 
      { 
       if (!(h1.ContainsKey(item))) 
        h1.Add(item, true); 
      } 

     } 
     Console.WriteLine(listofitemstoremove.Capacity); 
    } 

    public bool checkifthatvalueisfilled(int key) 
    { 
     if (h1.ContainsValue(h1.ContainsKey(key)) == true) 
      return true; 
     else return false; 
    } 

} 
+1

您的問題目前*非常*不清楚。你的代碼使用了幾個根本沒有解釋的變量和方法,你的文本解釋很難理解。請澄清。 – 2013-03-07 04:41:34

+1

一個猜測......將'current'指定給開始if(ele.Equals(b.Last())'? – 2013-03-07 04:47:02

+0

是否要在Dictionary中搜索某些值 – 2013-03-07 05:18:41

回答

0

你的問題很難理解。也許這就是你在循環開始時想做的事情?

current = h1.GetEnumerator(); 
current.MoveNext(); 
+0

解釋我做current.movenext()。但是在迭代之後,我希望當前指向字典中的第一個元素,該元素具有鍵,值爲(0,6)。但是我們知道,一旦我們迭代字典,在最後一個元素放入時,當我們執行current.movenext()。指向原始變量。 – user2142681 2013-03-07 05:04:17

0

如果我正確理解你的問題,你不能這樣做。枚舉器讓您連續訪問集合,這就是整個觀點。你不能突然將它移動到特定的元素,而不是從頭開始迭代到該元素。

另外我沒有看到一個很好的理由使用枚舉。如果你需要參考你算法的先前和當前元素 - 你應該存儲他們的密鑰而不是枚舉器。此外Im相當肯定的是,這些行

while ((current.Current.Value >= ele)) 
      { 
       //assign previous to current 
       previous = current; 
       //move current to next position 
       current.MoveNext(); 
      } 

一)將拋出一個異常,當你會到達集合體B不會工作的)結束,因爲你是分配基準類型如預期

0

我不是確保我明白你的問題,但也許你想改變這一點:

   previous = current; 

要這樣:

   previous.MoveNext(); 

這種方式'以前'將永遠比'當前'落後一步。如果按照原始代碼中的方式分配變量,則只需對兩個「當前」對象進行引用,然後對其進行遞增。