advertisement
Collections in C Sharp(C#) Programming
Collections
A collection is a set of related data that may not necessarily belong to the same data type. It can be set or modified dynamically at run-time. Accessing collections is similar to accessing arrays, where elements are accessed by their index numbers. However, there are differences between arrays and collections in C#.
Differences between arrays and collections.
Arrays:-
- It cannot be resized at run-time.
- The individual elements are of the same data type.
- Do not contain any methods for operations on elements.
Collections:-
- Can be resized at run-time.
- The individual elements can be of different data types.
- Contains methods for operations on elements.
1. System. Collections Namespace
The System. Collections namespace in C# allows you to construct and manipulate a collection of objects. This collection can include elements of different data types. The System. Collections namespace defines various collections such as dynamic arrays, lists, and dictionaries. The System. Collections namespace consists of classes and interfaces that define different collections.
The Commonly used classes and interfaces in the System. Collections namespace.
- ArrayList Class: Provides a collection that is similar to an array except that the items can be dynamically added and retrieved from the list and it can contain values of different types.
- Stack Class: Provides a collection that follows the last-in-first-out(LIFO) principle, which means the last item inserted in the collection, will be removed first.
- Hashtable Class: Provides a collection of key and value pairs that are arranged, based on the hash code of the key.
- SortedList Class: Provides a collection of key and value pairs where the items are sorted, based on the keys,
- IDictionary Interface: Represent a collection consisting of key/value pairs.
- IDictionaryEnumerator Interface: List the dictionary elements.
- IEnumerable Interface: Define an enumerator to perform iteration over a collection.
- ICollection Interface: Specifies the size and synchronization methods for all collections.
- IEnuerrator Interface: Supports iteration over elements of the collection.
- IList Interface: Represents a collection of items that can be accessed by their index number.
2. System. Collections. Generic Namespace
Consider an online application form used by students to register for an examination conducted by a university. The application form can be used to apply for examination of any course offered by the university. Similarly, in C#, generics allow you to define data structures that consist of functionalities that can be implemented for any data type. Thus, generics allow you to reuse a code for different data types.
To create generics, you should use the built-in classes of the System. Collections. Generic namespace. These classes ensure type-safety, which is a feature of C# that ensures a value is treated as the type with which it is declared.
Note: The System. Collections. Generic namespace is similar to the System. Collections namespace allows you to create collections. However, generic collections are type-safe.
3. Classes and Interfaces
The System. Collections. Generic namespace consists of classes and interfaces that define different generic collections.
Classes:-
The System. Collections. Generic namespace consists of classes that allow you to create type-safe collections.
- List<T>: Provides a generic collection of the items that can be dynamically resized.
- Stack<T>: Provides a generic collection that follows the LIFO principle, which means that the last item inserted in the collection will be removed first.
- Queue<T>: Provides a generic collection that follows the IFO principle, which means that the first item inserted in the collection will be removed first.
- Dictionary<K, V>: Provides a generic collection of keys and values.
- SortedDictionary<K, V>: Provides a generic collection of sorted key and value pairs that consists of items sorted items sorted according to their key.
- LinkedList<T>: Implements the doubly linked list by storing elements in it.
Interface and structure:-
The system.Collections.Generic namespace consists of an interface and structure that can be implemented to create type-safe collections.
- Icollection Interface: defines methods to control different generic collections.
- IEnumerable Interface: This is an interface that defines an enumerator to perform an iteration of a collection of a specific type.
- IComparer Interface: This is an interface that defines a method to compare two objects.
- IDictionary Interface: Represents a generic collection consisting of the key and value pairs.
- IEnumerator Interface: Supports simple iteration over elements of the generic collections.
- IList Interface: Represent a generic collection of items that can be accessed using the index position.
- Dictionary.Enumerator.Structure: List the elements of a dictionary.
- Dictionary.KeyCollection.Enumerator Structure: Lists the elements of a Dictionary.KeyCollection
- Dictionary.ValueCollection.Enumerator Structure: Lists the elements of a Dictionary.ValueCollection
- Key/ValuePair Structure: Define key/value pairs.
4. ArrayList Class
The ArrayList class is a variable-length array, that can dynamically increase or decrease in size. Unlike the Array class, this class can store elements of different data types. The ArrayList class allows you to specify the size of the collection, during program execution.
The ArrayList class allows you to define the capacity that specifies the number of elements an array list can contain. However, the default capacity of an ArrayList class is 16. If the number of elements in the list reaches the specified capacity, the capacity of the list gets doubled automatically. It can accept null values and can also include duplicate elements.
The ArayList class allows you to add, modify, and delete any element in the list even at run-time. The elements in the ArrayList can be accessed by using the index position. While working with the ArrayList class, you do not have to bother about freeing up the memory.
The ArrayList class consists of different methods and properties. These methods and properties are used to add and manipulate the elements of the list.
Methods:-
The methods of the ArrayList class allow you to perform actions such as adding, Removing, and copying elements in the list.
- Add: Adds an element at the end of the list.
- Remove: removes the specified elements that have occurred for the first time in the list.
- RemoveAT: Removes the element present at the specified index position in the list.
- Insert: Insert an element into the list at the specified index positions.
- Contains: Determines the existence of a particular element in the list.
- Indexof: Returns the index position of an element occurring for the first time in the list.
- Reverse: Reverse the values stored in the ArrayList.
- Sort: Rearranging the elements in an ascending position.
Properties:-
The properties of the ArrayList class allow you to count or retrieve the elements in the list.
- Capacity: Specifies the number of the elements the list can contain.
- Count: Determines the number of elements present in the list.
- Item: Retrieves or sets value at the specified position.
5. Hashtable Class
Consider the reception area of a hotel where you find the keyholder storing many keys. Each key on the keyholder uniquely identifies a room and thus, each room is uniquely identified by its key.
Similar to the keyholder, the Hashtable class in C# allows you to create collections in the form of keys and values. It generates a hashtable that associates keys with their corresponding values. The Hashtable class uses the hashtable to retrieve values associated with their unique key. The hashtable generated by the Hashtable class uses the hashing technique to retrieve the corresponding value of a key. Hashing is a process of generating the hash code for the key. The code is used to identify the corresponding value of the key.
The Hashtable object takes the key to search the value, performs a hashing function, and generates a hash code for that key. When you search for a particular value using the key, the hash code is used as an index to locate the desired record. For example, a student's name can be used as a key to retrieve the student ID and the corresponding residential address.
The hashtable class consists of different methods and properties that are used to add and manipulate the data within the hashtable.
Methods:-
The methods of the hashtable class allow you to perform certain actions on the data in the hashtable.
- Add: Adds an element with the specified key and value
- Remove: Removes the element having the specified key
- CopyTo: Copies elements of the hashtable to an array at the specified index
- ContainsKey: Checks whether the hashtable contains the specified key
- ContainsValue: Checks whether the hashtable contains the specified value
- GetEnumerator: Returns an IDictionaryEnumerator that traverses through the Hashtable
Properties:-
The properties of the Hashtable class allow you to access and modify the data in the hashtable.
- Count: Specifies the number of key and value pairs in the hashtable
- Item: Specifies the value, add a new value, or modifies the existing value for the specified key
- Keys: Provides an Icollection consisting of keys in the hashtable.
- Values: Provides an ICollect consisting of values in the hashtable.
- IsReadOnly: checks whether the Hashtable is read-only.
6. SortedList Class
The SortedList class represents a collection of key and value pairs where elements are sorted according to the key. By default, the SortedList class sorts the elements in ascending order, however, this can be changed if an IComparable object is passed to the constructor of the SortedList class. These elements are either accessed using the corresponding keys or the index numbers.
If you access elements using their keys, the sorted list class behaves like a hashtable, whereas if you access elements based on their index number, it behaves like an array.
The Sorted List class consists of different methods and properties that are used to add and manipulate the data in the sorted list.
Methods:-
The methods of the Sortedtist class allow you to perform certain actions on the data in the sorted list.
- Add: Adds an element to the sorted list with a specified key and value
- Remove: Removes the element having a specified key from the sorted list
- GetKey: Returns the key at the specified index position
- GetByIndex: Returns the value at the specified index position
- ContainsKey: Checks whether the instance of the SortedList class contains the specified key
- ContainsValue: Checks whether the instance of the sorted list class contains the specified value
- RemoveAt: Deletes the element at the specified index
Properties:-
The properties of the SortedList class allow you to access and modify the data in the sorted list.
- Capacity: Specifies the number of elements the sorted list can contain
- Count: Specifies the number of elements in the sorted list
- Item: Returns the value, adds a new value, or modifies existing value for the specified key
- Keys: Returns the keys in the sorted list
- Values: Returns the values in the sorted Iist
7. Dictionary Generic Class
The System. Collections. Generic namespace contains a vast number of generic collections. One of the most commonly used among these is the Dictionary generic class. It consists of a generic collection of elements organized in key and value pairs. It maps the keys to their corresponding values. Unlike other collections in the System. Collections namespace is used to create a collection of a single data type at a time.
Every element that you add to the dictionary consists of a value, which is associated with its key. You can retrieve a value from the dictionary by using its key.
Note: The Dictionary class does not allow null values as elements. The capacity of the Dictionary class is the number of elements that it can hold. However, as the elements are added, the capacity is automatically increased.
The dictionary generic class consists of different methods and properties that are used to add and manipulate elements in a collection.
Methods:-
The methods of the Dictionary generic class allow you to perform certain actions on the data in the collection.
- Add: Adds the specified key and value in the collection
- Remove: Removes the value associated with the specified key
- ContainsKey: Checks whether the collection contains the specified key
- ContainsValue: Checks whether the collection contains the specified value
- GetEnumerator: Returns an enumerator that traverses through the Dictionary
- GetType: Retrieves the Type of the current instance
Properties:-
The properties of the Dictionary generic class allow you to modify the data in the collection.
- Count: Determines the number of key and value pairs in the collection
- Item: Returns the value, adds a new value, or modifies the existing value for the specified key
- Keys: Returns the collection containing the keys
- Values: Returns the collection containing the values
8. Collection Initializers
Collection initializers allow adding elements to the collection classes of the System. Collections and System. Collections. Generic namespaces that implement the IEnumerable interface using element initializers. The element initializers can be a simple value, an expression, or an object initializer. When a programmer uses a collection initializer, the programmer is not required to provide multiple Add () methods to add elements to the collection, making the code concise. It is the responsibility of the compiler to provide the Add ) methods when the program is compiled.
advertisement
Conversation
Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!
Join the discussion and share your insights now!
Comments 0