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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With