【发布时间】:2013-02-01 18:05:49
【问题描述】:
我有一本字典,我必须检查一个条件直到字典的最后一个元素。我使用了 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);
}
}
}
【问题讨论】:
-
它抛出了什么异常?
-
@Anonymiser:我看到你在“使用”System.Linq。当然,那里已经有方法可以为您提供所需的结果。我很难理解你想要的确切结果。你能提供一个输入(我猜是
A和B)和输出吗? -
@syedmohsin,显然“在迭代时修改了集合” - 正如预期的那样。现在,由于缺少问题,因此不清楚 Anonymiser 是否想要此异常或需要做其他事情。
标签: c# collections dictionary hashtable enumeration