gpt4 book ai didi

c# - 在迭代 HashSet 时更改项的值

转载 作者:行者123 更新时间:2023-11-30 22:33:16 25 4
gpt4 key购买 nike

我正在使用 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);
}

}

提前感谢您的帮助

最佳答案

您不能在迭代时修改容器。解决方案是使用 LINQ ( Enumerable.Select ) 将初始集投影到“修改后的”集,并根据投影结果创建一个新的 HashSet

因为如果有一个带有适当签名的 func,您可以直接将它粘贴到 Enumerable.Select 方法中,并且由于 HashSet 有一个接受 IEnumerable<T>constructor,所以这一切都归结为一行:

var modifiedHashSet = new HashSet(myHashSet.Select(func));

关于c# - 在迭代 HashSet 时更改项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8377085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com