コレクション内のすべての要素をC#のHashSetから削除します
HashSetからコレクション内のすべての要素を削除するには、コードは次のとおりです-
例
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<string> set1 = new HashSet<string>();
set1.Add("Ryan");
set1.Add("Tom");
set1.Add("Andy");
set1.Add("Tim");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1){
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("John");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("Elements in HashSet2...");
foreach (string res in set2){
Console.WriteLine(res);
}
Console.WriteLine("Is HashSet1 equal to HashSet2? = "+set1.Equals(set2));
set2.ExceptWith(set1);
// displaying elements in set2, which are not on set1
foreach(string i in set2){
Console.WriteLine(i);
}
}
} 出力
これにより、次の出力が生成されます-
Elements in HashSet1... Ryan Tom Andy Tim Elements in HashSet2... John Jacob Ryan Tom Andy Tim Steve Mark Is HashSet1 equal to HashSet2? = False John Jacob Steve Mark
例
別の例を見てみましょう-
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args){
HashSet<string> set1 = new HashSet<string>();
set1.Add("Jacob");
set1.Add("Ryan");
set1.Add("Tom");
set1.Add("Andy");
set1.Add("Tim");
set1.Add("Steve");
set1.Add("Mark");
Console.WriteLine("Elements in HashSet1...");
foreach (string res in set1){
Console.WriteLine(res);
}
HashSet<string> set2 = new HashSet<string>();
set2.Add("Kevin");
set2.Add("Jacob");
set2.Add("Ryan");
set2.Add("Tom");
set2.Add("Andy");
set2.Add("Tim");
set2.Add("Steve");
set2.Add("Mark");
Console.WriteLine("Elements in HashSet2...");
foreach (string res in set2){
Console.WriteLine(res);
}
Console.WriteLine("Is HashSet1 equal to HashSet2? = "+set1.Equals(set2));
set2.ExceptWith(set1);
// displaying elements in set2, which are not on set1
foreach(string i in set2){
Console.WriteLine(i);
}
}
} 出力
これにより、次の出力が生成されます-
Elements in HashSet1... Jacob Ryan Tom Andy Tim Steve Mark Elements in HashSet2... Kevin Jacob Ryan Tom Andy Tim Steve Mark Is HashSet1 equal to HashSet2? = False Kevin
-
C#のコレクションから要素を取得する
リストコレクションの例を見てみましょう。 要素を設定しました- List<int> list = new List<int>(); list.Add(20); list.Add(40); list.Add(60); list.Add(80); ここで、リストから最初の要素を取得する必要があるとします。そのためには、このようにインデックスを設定します- int a = list[0]; 以下は、リストコレクションから要素を取得する方法を示す例です- 例 using System; using System.Collections.Generic; class De
-
JavaのArrayListからすべての要素を削除します
JavaでArrayListからすべての要素を削除するには、最初にいくつかの要素を含むArrayListを作成します- ArrayList<Integer> arrlist = new ArrayList<Integer>(5); arrlist.add(25); arrlist.add(50); arrlist.add(75); arrlist.add(100); arrlist.add(150); arrlist.add(200); arrlist.add(250); それでは、すべての要素を削除しましょう- arrlist.clear(); 例 完全なコードを