0

我有一本字典,我必须检查一个条件,直到字典的最后一个元素。我使用了方法 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);
        }
    }
}
4

1 回答 1

2

迭代枚举时不能修改它。如中,

foreach(var item in someList)
{
   if (someCondition)
      someList.remove(item); // At run time you will get an exception saying that the collection was modified
}

在这些情况下,您通常存储您需要删除的东西的 id,然后通过迭代新集合来删除它们,

var itemsToRemove = new List<int>();
foreach(var item in someList)
{
   if (someCondition)
      itemsToRemove.Add(item.Id);
}

foreach(var id in itemsToRemove)
{
   var item = someList.First(l => l.Id = id)
   someList.Remove(item);
}
于 2013-02-17T01:47:01.290 回答