The Set<T> Type
The C# has a number of object types that offer more functionality thatn your standard primitive types. We will look at the List, Set, Dictionary, and File types.
LIst, Set, and Dictionary are known as Generic types (more on this in a further course).
Arrays are limited by their rigidity. You have to create them of a fixed size. You cannot alter their size once they have been created. The only way to access elements is throuh an zero based index.
Represents a strongly typed set of objects that can be accessed by index. It provides methods to search, sort, and manipulate the Set.
You cannot create a Set directly, it must either be a HashSet or a SortedSet.
Example | Result |
---|---|
HashSet<int> setOfAges = new HashSet<int>();
setOfAges.Add(33);
setOfAges.Add(56);
setOfAges.Add(29);
setOfAges.Add(33);
foreach (int age in setOfAges)
{
Console.Write($"{age} ");
}
| HashSet Create the Set object and bind it to the The In the foreach satement, each item in setOfAges is projected one by one into the age variable. Each time a value from setOfAges is projected into age the code block is executed with the current value in age. This repeats until all items within setOfAges have been exhausted. 33 56 29 will be printed |
SortedSet<int> setOfAges = new SortedSet<int>();
setOfAges.Add(29);
setOfAges.Add(56);
setOfAges.Add(33);
foreach (int age in setOfAges)
{
Console.Write($"{age} ");
}
| SortedSet Create the Set object and bind it to the The SortedSet will sort items as they are added to the collection 29 33 56 Will be printed  |
Â