迭代和修改字典
我正在试图解决在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;
}
}
你的问题很难理解。也许这就是你在循环开始时想做的事情?
current = h1.GetEnumerator();
current.MoveNext();
解释我做current.movenext()。但是在迭代之后,我希望当前指向字典中的第一个元素,该元素具有键,值为(0,6)。但是我们知道,一旦我们迭代字典,在最后一个元素放入时,当我们执行current.movenext()。指向原始变量。 – user2142681 2013-03-07 05:04:17
如果我正确理解你的问题,你不能这样做。枚举器让您连续访问集合,这就是整个观点。你不能突然将它移动到特定的元素,而不是从头开始迭代到该元素。
另外我没有看到一个很好的理由使用枚举。如果你需要参考你算法的先前和当前元素 - 你应该存储他们的密钥而不是枚举器。此外Im相当肯定的是,这些行
while ((current.Current.Value >= ele))
{
//assign previous to current
previous = current;
//move current to next position
current.MoveNext();
}
一)将抛出一个异常,当你会到达集合体B不会工作的)结束,因为你是分配基准类型如预期
我不是确保我明白你的问题,但也许你想改变这一点:
previous = current;
要这样:
previous.MoveNext();
这种方式'以前'将永远比'当前'落后一步。如果按照原始代码中的方式分配变量,则只需对两个“当前”对象进行引用,然后对其进行递增。
您的问题目前*非常*不清楚。你的代码使用了几个根本没有解释的变量和方法,你的文本解释很难理解。请澄清。 – 2013-03-07 04:41:34
一个猜测......将'current'指定给开始if(ele.Equals(b.Last())'? – 2013-03-07 04:47:02
是否要在Dictionary中搜索某些值 – 2013-03-07 05:18:41