簡體   English   中英

HashSet 在刪除 C# 中的項目時進行迭代

[英]HashSet Iterating While Removing Items in C#

我在 C# 中有一個哈希集,如果在迭代哈希集時滿足條件,我將刪除該哈希集,並且無法使用如下的 foreach 循環執行此操作。

foreach (String hashVal in hashset) 
{
     if (hashVal == "somestring") 
     {
            hash.Remove("somestring");
     }
}

那么,如何在迭代時刪除元素?

改為使用HashSet的RemoveWhere方法:

hashset.RemoveWhere(s => s == "somestring");

您指定條件/謂詞作為方法的參數。 將刪除散列集中與謂詞匹配的任何項。

這避免了在迭代過程中修改hashset的問題。


回應你的評論:

's'表示從hashset中計算的當前項。

上面的代碼相當於:

hashset.RemoveWhere(delegate(string s) {return s == "somestring";});

要么:

hashset.RemoveWhere(ShouldRemove);

public bool ShouldRemove(string s)
{
    return s == "somestring";
}

編輯:我剛剛發生了一些事情:因為HashSet是一個不包含重復值的集合,所以只需調用hashset.Remove("somestring") 沒有必要在循環中執行它,因為永遠不會有多個匹配。

使用枚舉器循環遍歷集合時,無法從集合中刪除項目。 解決這個問題的兩種方法是:

  • 使用常規索引for循環在集合上向后循環(我相信在HashSet的情況下不是一個選項)
  • 循環遍歷集合,將要刪除的項添加到另一個集合,然后遍歷“待刪除”集合並刪除項目:

第二種方法的示例:

HashSet<string> hashSet = new HashSet<string>();
hashSet.Add("one");
hashSet.Add("two");

List<string> itemsToRemove = new List<string>();
foreach (var item in hashSet)
{
    if (item == "one")
    {
        itemsToRemove.Add(item);
    }
}

foreach (var item in itemsToRemove)
{
    hashSet.Remove(item);
}

我會避免使用兩個foreach循環 - 一個foreach循環就足夠了:

HashSet<string> anotherHashSet = new HashSet<string>();
foreach (var item in hashSet)
{
    if (!shouldBeRemoved)
    {
        anotherSet.Add(item);
    }
}
hashSet = anotherHashSet;

通常當我想迭代某些東西並刪除我使用的值時:

 For (index = last to first)
      If(ShouldRemove(index)) Then
           Remove(index)

對於那些正在尋找一種方法來處理 HashSet 中的元素同時刪除它們的人,我按照以下方式進行了操作

var set = new HashSet<int> {1, 2, 3};

while (set.Count > 0)
{
  var element = set.FirstOrDefault();
  Process(element);
  set.Remove(element);
}

這里有一個更簡單的解決方案。

var mySet = new HashSet<string>();
foreach(var val in mySet.ToArray() {
   Console.WriteLine(val);
   mySet.Remove(val);
}

.ToArray() 已經為您創建了一個副本。 你可以循環到你的心內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM