我想知道是否有任何方法在遍历字典时存储键值对的枚举器的值。我想将枚举数的键和值存储在某个变量中。解决办法是什么?我想要做的是当迭代通过字典有一个当前键值对和字典中的下一个键值对的参考。我不知道为什么它不工作c中的词典迭代器#
这是什么解决方案可能看起来像:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace WellPuzzle
{
class Solution
{
Hashtable h1 = new Hashtable();
List<int> listofitemstoremove = new List<int>();
Dictionary<int, int> d1 = new Dictionary<int, int>();
public void falling_disks(int[] A, int[] B)
{
var itemstoremove = new List<int>();
var en = d1.GetEnumerator();
int count = 0;
for (int i = 0; i <= A.Length - 1; i++)
{
d1.Add(count++, A[i]);
}
//for each incoming element in array
foreach (int ele in B)
{
//store prev as current position of enumerator
var prev = new KeyValuePair<int, int>();
prev = en.Current;
//check if it is possible to iterate to next element in dictionary
if (en.MoveNext())
{
//loop till end of dictionary
while (en.MoveNext())
{
//if current value of enumerator in dictionary is less than incoming element and check if corroesponding key for that value is in hashtable or not
if (en.Current.Value <= ele && !(checkifthatvalueisfilled(en.Current.Key)))
continue;
else
{//if current enumerator value is greater than incoming element from array B then remove all elements from prev reference till end of dictionary
h1.Add(en.Current.Key, true);
listofitemstoremove.Add(en.Current.Key);
}
prev = en.Current;
}
if (!(h1.ContainsKey(en.Current.Key)))
{
h1.Add(en.Current.Key, true);
listofitemstoremove.Add(en.Current.Key);
}
}
else
{
h1.Add(prev.Key, true);
listofitemstoremove.Add(prev.Key);
}
foreach (int item in listofitemstoremove)
{
for (int i = item; i < d1.Count; i++)
{
d1.Remove(i++);
}
}
}
Console.WriteLine(h1.Count);
}
public bool checkifthatvalueisfilled(int value)
{
if (h1.ContainsValue(h1.ContainsKey(value)) == true)
return true;
else return false;
}
}
class Program
{
static void Main(string[] args)
{
int[] A = new int[] { 5, 6, 4, 3, 6, 2, 3 };
int[] B = new int[] { 2, 3 };
Solution s1 = new Solution();
s1.falling_disks(A, B);
}
}
}
你的代码为书面?当然不是。你有'en'键入到用于存储KeyValuePair的IEnumerator中,并且'next'试图存储void返回方法的结果。你究竟在努力完成什么?最终,而不是手段。 – 2013-02-18 18:05:10
看起来你试图把字典当作具有按序枚举器的东西(或者完全按顺序)。不要这样做。根据你想要的,你看过一个多维'int [,]'数组是否可以工作吗? – Earlz 2013-02-18 18:07:04
它看起来像你试图设置枚举器的当前位置,就像你将在C++中设置一个指针一样。如果这就是你想要的,那在C#中是不可能的;您只能将枚举数移至下一个项目;你不能把它设置成任意的项目。 – Servy 2013-02-18 18:07:11