Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete item from dictionary while iterating over it

I have problem with Dictionary(buzzCompaignsPerUserIntersets). I have dictionary (key = stringand value = ICollection), I want to remove from value of each key, campaign which verify condition here is the code that I used:

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

with this code I have a strange result because I iterate over a dictionary from which I remove elements.

like image 309
ucef Avatar asked Feb 15 '26 17:02

ucef


1 Answers

The use of ElementAt(i) is not the ideal way to get a particular item and will perform poorly. Its usage suggests that you want a collection with an indexer, such as IList<T>.

Using your current setup, you could use this approach:

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

Alternately, if you can change the ICollection<T> to an IList<T> you could use the indexer and the RemoveAt method. That would look like this:

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

A List<T> would let you use the RemoveAll method. If you're interested in how that works take a look at my answer to another question.

like image 131
Ahmad Mageed Avatar answered Feb 20 '26 03:02

Ahmad Mageed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!