2013-04-02 117 views
5

我想通過一個HashSet並對每個元素進行(複雜)檢查,從而導致保存元素,從HashSet中刪除元素或者什麼都不做。枚舉hashset並從中刪除元素

因爲foreach循環不允許我更改HashSet並且索引不可用,所以我不知道如何執行任務(不需要執行緩慢的操作(如先複製HashSet或應用多個表示枚舉的LINQ操作HashSet不止一次)。

有什麼建議嗎?

+1

'保存元素'你想在哪裏保存元素?假設什麼時候你什麼都不做,它將被保存在hashset中 –

+0

不,我想從一些優化意義上找到並保存HashSet中的「best」元素,在這裏我通過一個多步驟過程,刪除所有已經存在的元素超過了最佳可能值。 –

回答

7

你只需要使用RemoveWhere()與一個適當的謂詞函數。

如果需要,您可以使用謂詞的副作用來複制被檢查的元素(假設這就是「保存元素」的含義)。也許這聽起來有點冒失,但我認爲它會工作得很好。

這工作,因爲你的斷言函數將與HashSet中的每個元素未定義的順序呈現,因此,你可以決定做什麼用的每一個元素,以及返回true將其刪除,並false保留它。

[編輯]這是一個代碼示例。

using System; 
using System.Collections.Generic; 

namespace Demo 
{ 
    public class Program 
    { 
     [STAThread] 
     private static void Main(string[] args) 
     { 
      var hashSet = new HashSet<int> {4, 0, 6, -1, 23, -8, 14, 12, -9, 5, 2}; 
      var itemProcessor = new ItemProcessor(); 

      hashSet.RemoveWhere(itemProcessor.Process); 

      Console.WriteLine("Max = {0}, Min = {1}", itemProcessor.Max, itemProcessor.Min); 
      Console.WriteLine("\nHashSet contents:"); 

      foreach (int number in hashSet) 
      { 
       Console.WriteLine(number); 
      } 
     } 
    } 

    public sealed class ItemProcessor 
    { 
     private int max = int.MinValue; 
     private int min = int.MaxValue; 

     // Removes all negative numbers and calculates max and min values. 

     public bool Process(int item) 
     { 
      max = Math.Max(item, max); 
      min = Math.Min(item, min); 

      return (item < 0); 
     } 

     public int Max { get { return max; } } 
     public int Min { get { return min; } } 
    } 
}