// http://svc.luckstar.com.tw/CodeHelper/cs/index.html // 2017-03-22, honda@luckstar.com.tw, Create. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleBase { public class CHashSet { HashSet mList1 = new HashSet(); public void Run() { Console.WriteLine("Basic:"); Console.WriteLine("mList1:"); mList1.Add("s1"); mList1.Add("s2"); mList1.Add("s3"); if (!mList1.Contains("xxx")) mList1.Add("s4"); if (!mList1.Contains("s4")) mList1.Add("s5"); PrintHashSetS(mList1); Console.WriteLine(); PrintDashLine(); HashSet evenNumbers = new HashSet(); HashSet oddNumbers = new HashSet(); for (int i = 0; i < 5; i++) { // Populate numbers with just even numbers. evenNumbers.Add(i * 2); // Populate oddNumbers with just odd numbers. oddNumbers.Add((i * 2) + 1); } Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count); PrintHashSetI(evenNumbers); Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count); PrintHashSetI(oddNumbers); // Create a new HashSet populated with even numbers. HashSet numbers = new HashSet(evenNumbers); Console.WriteLine("numbers UnionWith oddNumbers..."); numbers.UnionWith(oddNumbers); Console.Write("numbers contains {0} elements: ", numbers.Count); PrintHashSetI(numbers); } private void PrintHashSetS(HashSet set) { Console.Write("{"); foreach (string s1 in set) { Console.Write(" {0}", s1); } Console.WriteLine(" }"); } private void PrintHashSetI(HashSet set) { Console.Write("{"); foreach (int i in set) { Console.Write(" {0}", i); } Console.WriteLine(" }"); } private void PrintDashLine() { Console.WriteLine(); Console.WriteLine("----------"); } } } result: Basic: mList1: { s1 s2 s3 s4 } ---------- evenNumbers contains 5 elements: { 0 2 4 6 8 } oddNumbers contains 5 elements: { 1 3 5 7 9 } numbers UnionWith oddNumbers... numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }