在迭代HashSet时更改术语的值

时间:2011-12-04 17:19:09

标签: c# hashset

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

}

提前感谢您的帮助

2 个答案:

答案 0 :(得分:2)

在迭代迭代时,您无法修改容器。解决方案是使用LINQ(Enumerable.Select)将初始集投影到“已修改”的集合中,并从投影结果中创建新的HashSet

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

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

答案 1 :(得分:1)

接受的答案确实是正确的,但如果在我的情况下,要求修改同一个实例,则可以遍历HashSet的副本。

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