HashSetset = new HashSet (); set.Add(3); set.Add(5); set.Add(3); // This won't be added since it's a duplicate foreach (int i in set) { Console.Write(i + " "); // Output: 3 5 }
SortedSetThis example uses SortedSet, another subtype of Set, to store strings in alphabetical order and retrieve a range of values using the GetViewBetween method. It demonstrates how SortedSet can be useful for maintaining an ordered collection of values. Both examples use the System.Collections.Generic namespace, which is part of the .NET Framework's class library.set = new SortedSet (); set.Add("apple"); set.Add("banana"); set.Add("cherry"); set.Add("pear"); foreach (string fruit in set.GetViewBetween("banana", "pear")) { Console.Write(fruit + " "); // Output: banana cherry }