Collections
C# includes various classes that store the values or objects called collections.
There are two types of collections available in C#
Non-generic collections and Generic collections
The System. The collections namespace contains the non-generic collection types and systems.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use the generic collections because they perform faster than non-generic collections and also minimize exceptions by giving compile-time errors.
Generic Collections
- HashSet
- Sorted List
- Dictionary
- List
HashSet
It is a collection of unique elements. if you add duplicate data, then it shows only one unique value inside the collection.
HashSet<string> myhash1 = new HashSet<string>();
// Add the elements in HashSet
// Using Add method
myhash1.Add("C");
myhash1.Add("C++");
myhash1.Add("C#");
myhash1.Add("Java");
myhash1.Add("Ruby");
Console.WriteLine("Elements of myhash1:");
// Accessing elements of HashSet
// Using foreach loop
foreach(var val in myhash1)
{
Console.WriteLine(val);
}
Access single elements
if (myhash1.Count > 0)
Console.WriteLine(myhash1.ToList()[1]);
Remove element
myhash.Remove("Ruby");
Sorted list
It is a collection of key/value pairs that are sorted according to keys. By default, this collection sorts the key/value pairs in ascending order.
Syntax
SortedList list_name = new SortedList();
Example
SortedList my_slist1 = new SortedList();
// Adding key/value pairs in
// SortedList using Add() method
my_slist1.Add(1.02, "This");
my_slist1.Add(1.07, "Is");
my_slist1.Add(1.04, "SortedList");
my_slist1.Add(1.01, "Tutorial");
Happy Coding!
Thanks.