迭代并修改字典

时间:2013-03-07 04:38:25

标签: c# asp.net dictionary hashtable ienumerator

我正在尝试为http://users.metropolia.fi/~dangm/blog/?p=67上显示的问题实施解决方案。 我是c#language的新手。我想使用枚举器和特定条件迭代字典。所以有两个变量current和previous.current指向dictionary.previous的第一个元素指向dictionary.Bhile迭代字典我像foll一样迭代

previous=current;
current.MoveNext();

问题是当我们第一次通过整个字典迭代前一个点到字典中的最后一个元素并且当前点指向随机键值对RawVariable(0,0)。但是现在当我们第二次通过字典迭代时我希望当前指向在dictionary.how中的第一个元素我是否将当前点指向具有特定键或值的某个元素

这是我的代码段

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

}

3 个答案:

答案 0 :(得分:0)

您的问题很难理解。也许这就是你想在循环开始时做的事情?

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

答案 1 :(得分:0)

如果我理解你的问题,你就无法做到。 Enumerator为您提供对集合的连续访问权限,这就是重点。你不能突然将它移动到特定的元素,而不是从头开始迭代到那个元素。

Futheremore我没有看到使用枚举器的一个好理由。如果您需要为您的算法引用先前和当前元素,则应存储其键,而不是枚举器。我也很确定这些行

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

a)将抛出异常,当你到达集合的末尾时b)因为你正在分配引用类型而无法正常工作

答案 2 :(得分:0)

我不确定我理解你的问题,但也许你想改变这个:

                previous = current;

对此:

                previous.MoveNext();

那样'以前'总是比'当前'落后一步。如果按照原始代码中的方式分配变量,则只需要对“当前”对象进行两次引用,然后递增。