字典中的迭代

时间:2013-02-17 01:40:08

标签: c# collections dictionary hashtable enumeration

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

1 个答案:

答案 0 :(得分: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);
}