迭代 HashSet 时更改项的值
我正在使用 HashSet 以避免在我的集合中出现两个(或更多)具有相同值的项目,在我的工作中,我需要迭代我的哈希集并删除其值,但不幸的是我不能这样做,我正在尝试要做的是:
string newValue = "";
HashSet<string> myHashSet;
myHashSet = GetAllValues(); // lets say there is a function which fill the hashset
foreach (string s in myHashSet)
{
newValue = func(s) // lets say that func on some cases returns s as it was and
if(s != newValue) // for some cases returns another va
{
myHashSet.Remove(s);
myHashSet.Add(newValue);
}
}
提前感谢您的帮助
i am using a HashSet in order to avoid having two (or more)items with the same value inside my collection , on my work i need to iterate over my hashset and remove its values but unfortunatly i cant do so , what i am trying to do is:
string newValue = "";
HashSet<string> myHashSet;
myHashSet = GetAllValues(); // lets say there is a function which fill the hashset
foreach (string s in myHashSet)
{
newValue = func(s) // lets say that func on some cases returns s as it was and
if(s != newValue) // for some cases returns another va
{
myHashSet.Remove(s);
myHashSet.Add(newValue);
}
}
thanks in advance for your kind help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法在迭代容器时对其进行修改。解决方案是使用 LINQ 将初始集投影到“修改的”集中 (< code>Enumerable.Select),并根据投影结果创建一个新的
HashSet
。因为如果存在具有适当签名的
func
,您可以直接将其粘贴到Enumerable.Select
方法中,并且由于HashSet
有一个 构造函数 接受IEnumerable
,这一切都归结为一行:You cannot modify the container while it's being iterated. The solution would be to project the initial set into a "modified" set using LINQ (
Enumerable.Select
), and create a newHashSet
from the results of the projection.Since if there is a
func
with the appropriate signature you can directly stick it into theEnumerable.Select
method, and sinceHashSet
has a constructor that accepts anIEnumerable<T>
, it all comes down to one line:接受的答案确实是正确的,但如果像我的情况一样,您需要修改同一实例,则可以迭代
HashSet
的副本。The accepted answer is indeed correct, but if, as in my case, you require modification of the same instance, you can iterate through a copy of the
HashSet
.