3

我有问题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));         
      }                
}

使用这段代码,我得到了一个奇怪的结果,因为我遍历了一个从中删除元素的字典。

4

2 回答 2

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);
         }
     }
}

AList<T>会让你使用该RemoveAll方法。如果您对它的工作原理感兴趣,请查看我对另一个问题的回答

于 2012-07-06T19:09:37.297 回答
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);
}
于 2012-07-06T16:48:30.847 回答