从字典中删除项目,同时迭代它 [英] delete item from dictionary while iterating over it
问题描述
我有字典(buzzCompaignsPerUserIntersets),我有字典(key = stringand value = ICollection),我想删除从每个键的值,compaign wich验证条件这里是我使用的代码:
ihave probleme with Dictionary(buzzCompaignsPerUserIntersets) , i have dictionary (key = stringand value = ICollection), i want to remove from value of each key , compaign wich verify condition here is the code who 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 strange result because i iterate over a dictionary wich i remove element from them , have you any suggestion
推荐答案
使用 ElementAt )
不是获取特定项目的理想方式,并且性能不佳。它的用法建议你想要一个索引器的集合,如 IList< T>
。
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>
.
您可以使用这种方法:
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
方法。它看起来像这样:
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>
将允许您使用 RemoveAll
方法。如果您对这项工作感兴趣,请参阅我对另一个问题的回答。
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.
这篇关于从字典中删除项目,同时迭代它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!