迭代它时从字典中删除项目

时间:2012-07-06 15:58:32

标签: c#-4.0 dictionary

我有使用Dictionary(buzzCompaignsPerUserIntersets)的问题,我有字典(key = stringand value = ICollection),我想从每个键的值中删除,在这里验证验证条件是我使用的代码:

      buzzCompaignsPerUserIntersets = Dictionary<string, ICollection<Buzzcompaign> ;

        foreach(var dic_compaign in buzzCompaignsPerUserIntersets)
        {

             var listCompaign = buzzCompaignsPerUserIntersets[dic_compaign.Key];
             for (int i = 0; i < listCompaign.Count(); i++)
             {
                 if (listCompaign.ElementAt(i).MayaMembership.MayaProfile.MayaProfileId == profile_id)
                                 buzzCompaignsPerUserIntersets[dic_compaign.Key].Remove(listCompaign.ElementAt(i));         
              }                
        }

使用此代码我有奇怪的结果,因为我迭代一个字典,我从他们删除元素,你有任何建议

2 个答案:

答案 0 :(得分:2)

使用ElementAt(i)并不是获得特定项目的理想方式,而且表现不佳。它的用法表明你想要一个带有索引器的集合,例如IList<T>

使用您当前的设置,您可以使用此方法:

foreach(var key in buzzCompaignsPerUserIntersets.Keys)
{
     var list = buzzCompaignsPerUserIntersets[key];
     var query = list.Where(o => o.MayaMembership
                                  .MayaProfile.MayaProfileId == profile_id)
                     .ToArray();
     foreach (var item in query)
     {
         list.Remove(item);
     }
}

或者,如果您可以将ICollection<T>更改为IList<T>,则可以使用索引器和RemoveAt方法。这看起来像这样:

foreach(var key in buzzCompaignsPerUserIntersets.Keys)
{
     var list = buzzCompaignsPerUserIntersets[key];
     for (int i = list.Count - 1; i >= 0; i--)
     {
         if (list[i].MayaMembership.MayaProfile.MayaProfileId == profile_id)
         {
             list.RemoveAt(i);
         }
     }
}

List<T>可让您使用RemoveAll方法。如果您对如何运作感兴趣,请查看my answer to another question

答案 1 :(得分:0)

尝试这样的事情

foreach(var dic_compaign in buzzCompaignsPerUserIntersets) 
{ 
   buzzCompaignsPerUserIntersets[dic_compaign.Key].RemoveAll(
     dic_campaign.Value.FindAll(
       delegate(ListCampaignType item) 
       { return item.MayaMembership.MayaProfile.MayaProfileId == profile_id; })
   );
} 

ListCampaignType是词典中的值类型。

基本上你不能改变你正在迭代的集合,所以做上述事情的方法很长。

foreach(var dic_compaign in buzzCompaignsPerUserIntersets) 
{ 
   List<ListCampaignType> itemstoremove = new List<ListCampaignType>();
   foreach(var item in buzzCompaignsPerUserIntersets[dic_compaign.Key])
   {
      if (item.MayaMembership.MayaProfile.MayaProfileId == profile_id)
      {
         itemstoremove.Add(item);
      }
   }
   buzzCompaignsPerUserIntersets[dic_compaign.Key].RemoveAll(itemstoremove);
}