迭代 HashSet 时更改项的值

发布于 2024-12-19 14:34:06 字数 551 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾铮苏瑾 2024-12-26 14:34:06

您无法在迭代容器时对其进行修改。解决方案是使用 LINQ 将初始集投影到“修改的”集中 (< code>Enumerable.Select),并根据投影结果创建一个新的 HashSet

因为如果存在具有适当签名的 func ,您可以直接将其粘贴到 Enumerable.Select 方法中,并且由于 HashSet 有一个 构造函数 接受IEnumerable,这一切都归结为一行:

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

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 new HashSet from the results of the projection.

Since if there is a func with the appropriate signature you can directly stick it into the Enumerable.Select method, and since HashSet has a constructor that accepts an IEnumerable<T>, it all comes down to one line:

var modifiedHashSet = new HashSet(myHashSet.Select(func));
夏花。依旧 2024-12-26 14:34:06

接受的答案确实是正确的,但如果像我的情况一样,您需要修改同一实例,则可以迭代HashSet的副本。

foreach (string s in myHashSet.ToArray()) // ToArray will create a copy
{
   newValue = func(s)
   if(s != newValue)
   {
         myHashSet.Remove(s);
         myHashSet.Add(newValue);
   }
}

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.

foreach (string s in myHashSet.ToArray()) // ToArray will create a copy
{
   newValue = func(s)
   if(s != newValue)
   {
         myHashSet.Remove(s);
         myHashSet.Add(newValue);
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文