用 C# 中由謂詞定義的條件從 HashSet 中刪除元素


要從 HashSet 中刪除符合謂詞定義的條件的元素,程式碼如下

示例

 線上演示

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return (i == 100);
   }
   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(300);
      list.Add(400);
      list.Add(500);
      list.Add(600);
      Console.WriteLine("HashSet elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveWhere(demo);
      Console.WriteLine("HashSet after removing element 100...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

輸出

它將產生以下輸出

HashSet elements...
100
300
400
500
600
HashSet after removing element 100...
300
400
500
600

示例

讓我們看另一個示例

using System;
using System.Collections.Generic;
public class Demo {
   private static bool demo(int i) {
      return ((i % 10) == 0);
   }
   public static void Main(String[] args) {
      HashSet<int> list = new HashSet<int>();
      list.Add(100);
      list.Add(355);
      list.Add(400);
      list.Add(555);
      list.Add(600);
      Console.WriteLine("HashSet elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
      Console.WriteLine(" ");
      list.RemoveWhere(demo);
      Console.WriteLine("HashSet after removing some elements...");
      foreach (int i in list) {
         Console.WriteLine(i);
      }
   }
}

輸出

它將產生以下輸出

HashSet elements...
100
355
400
555
600
HashSet after removing some elements...
355
555

更新時間:05-Dec-2019

253 瀏覽量

開啟你的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.