Collections in c#
Collections standardize the way your program handles objects. In other words, it has several classes that allow items to be contained in a more generalized way. The user can store, update, remove, retrieve, search, sort, and perform other activities on objects with the su
Collections in c#
Collections standardize the way your program handles objects. In other words, it has several classes that allow items to be contained in a more generalized way. The user can store, update, remove, retrieve, search, sort, and perform other activities on objects with the support of collections.
Collections are divided into numerous classes in C#, some of the more popular classes are listed below and they are:
1. System.Collections.Generic
2. System.Collection
3. System.Collections.Concurrent
1. System.Collections.Generic Classes:
In C#, a generic collection is defined in System.Collection.Generic namespace. There is a general implementation for common data structures including linked lists, stacks, queues, and dictionaries. Because they are generic, these collections are type safe.
They prevent unintentional type mismatches by only allowing objects that are type-compatible with the collection's type to be stored there. The group of classes and interfaces that make generic collections define them. The frequently used classes are listed in the below System.Collections.General namespace:
Class name and Description:
1. Dictionary<TKey,TValue>:
It offers functionality and stores key-value pairs like the non-generic Hashtable class.
2. List<T>:
It is a dynamic array with capabilities comparable to the non-generic ArrayList class.
3. Queue<T>:
A first-in, first-out List with identical capabilities to the non-generic Queue class is provided.
4. SortedList<TKey,TValue>:
It has comparable functionality to the non-generic SortedList class and is a sorted list of key/value pairs.
5. Stack<T>:
It has first-in, last-out ordering and offers features comparable to those of the non-generic Stack class.
6. HashSet<T>:
It is an unorganized grouping of individual features.
7. LinkedList<T>:
It enables quick element insertion and removal. It implements a classic linked list.
Example:
The code for the program is as follows:
CODE:
using System; using System.Collections.Generic; class Preethi { // Main Method public static void Main(String[] args) { // Creating a List of integers List<int> mylist = new List<int>(); // adding items in mylist for (int j = 5; j < 10; j++) { mylist.Add(j * 3); } // Displaying items of mylist // by using for-each loop foreach(int items in mylist) { Console.WriteLine(items); } } }
OUTPUT:
The Output of the following code will be:
2.System.Collections Classes
System.Collections namespace in C# contains definitions for non-generic collections. It can handle any object because it is a general-purpose data structure that operates on object references but not in a safe-type manner. The collection of interfaces and classes defines non-generic collections. The System's most used classes are listed in the table below. Namespace for collections:
Class name and Description:
1.ArrayList:
Since it is a dynamic array, its size might change rather than it is being fixed. It represents a group of objects so that each can be indexed separately.
It serves as an array's substitute. Unlike an array, which automatically resizes, an index allows you to add and remove items from a list at a particular place. Additionally, it allows for dynamic memory allocation in addition to adding, searching, and sorting list items.
2.Hashtable:
It represents a set of key-and-value pairs arranged according to the key's hash code. To access the collection's elements, it utilizes a key. The collection's items can be accessed using the key.
3.Sorted List:
To access the items in a list, you need a key and an index. A sorted list is made by combining a hash table and an array.
It contains a list of items that can be found using an index or a key. It is an ArrayList if you access things using an index; a Hashtable if you use a key. The critical value is always used to order the group of items.
4. Queue:
It represents a first-in, first-out collection of items. When first-in, first-out access to items is required, it is used.
5. Stack:
This data structure is linear. The Last In, First Out (LIFO) input/output pattern is used. It displays an object collection in which last-in, first-out order.
When you require last-in, first-out access to objects, you use it. Pushing and popping are the terms used to describe adding and removing items from a list.
6. BitArray:
It displays a binary representation array using the values 1 and 0. When you need to store the bits you need to know the exact quantity, to use it. The BitArray collection's items can be accessed using an integer index starting at zero.
Example:
The code for the program is as follows:
CODE:
using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("C#"); myQueue.Enqueue("PHP"); myQueue.Enqueue("Perl"); myQueue.Enqueue("Java"); myQueue.Enqueue("C"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements present in the Queue are: "); Console.WriteLine(myQueue.Count); // Displaying the beginning element of the Queue Console.WriteLine("Beginning Item is: " + myQueue.Peek()); } }
OUTPUT:
The Output of the following code will be:
NOTE: The System.Collections.Specialized namespace in C# contains various specialized collections designed to deal with a particular data type.
3.System.Collections.Concurrent:
It was available from the.NET Framework Version 4 ahead. Several thread-safe collection classes are provided in place of the corresponding System.Collections. When several threads are simultaneously accessing the collection, use generic namespaces. This collection's classes include the following:
Class name and Description:
1.BlockingCollection:
It offers thread-safe collections that implement IProducerConsumerCollection blocking and bounding features.
2. ConcurrentBag:
It stands for an unordered, thread-safe collection of things.
3. ConcurrentDictionary:
It represents a collection of concurrently accessible key/value pairs that is thread-safe.
4. ConcurrentQueue:
It stands for a thread-safe first-in, first-out (FIFO) collection.
5. ConcurrentStack:
It represents a thread-safe last-in, first-out (LIFO) collection.
6. OrderablePartitioner:
It represents a specific approach to partitioning an orderable data source into several parts.
7. Partitioner:
It includes a standard array, List, and enumerable partitioning approaches. It represents a specific approach to dividing a data source into multiple parts.
- Collections are groups of objects in C#. Collections enable us to conduct several operations on objects, including:
- In C#, the collection represents a group of objects. With the help of collections, we can perform various operations on objects, such as
- store object
- update object
- delete object
- retrieve object
- search object, and
- sort object
- C# collections can handle all the data structure which works in sort.
- Objects can be kept in an array or collection. Over array, the collection has an advantage.
- While objects kept in collections can expand or decrease dynamically, arrays have a size limit.
- Collection classes are focused classes for storing and retrieving data.
- Collection classes can be used for a number of purposes, such as index-based access to lists of items and dynamic memory allocation for elements.
- These classes build collections of Object class objects, the foundation for all other C# data types.
An easy way to work with groups of objects is through collections. As the requirements of the application change, unlike arrays, the group of objects you interact which can expand and contract dynamically. Some collections allow you to assign a key to any object you add. This key can be utilized to retrieve the object quickly.
Since a collection is a class, an instance must be declared before the items can be added.
Using a Simple Collection:
A collection initializer can be used to initialize a collection if its contents are known in advance. For more details observe object and collection initializers.
The generic List in the following example has its elements removed. The statement that iterates in descending order is used in place of a for each statement. This is so that elements that come after a removed element have a lower index value due to the RemoveAt method.
The code for the program is as follows:
CODE:
var numbers = new List <int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Remove odd numbers. for (var index = numbers.Count - 1; index >= 0; index--) { if (numbers[index] % 2 == 1) { // Remove the element by specifying // the zero-based index in the List. numbers.RemoveAt(index); } } // Iterate through the List. // A lambda expression is placed in the ForEach method // of the List(T) object. numbers.ForEach( number => Console.Write(number + " "));
OUTPUT:
The Output of the program will be:
0 2 4 6 8
You can declare your class for the elements in the ListT> according to their kind. The Galaxy class, used by the ListT> in the example below, is defined in the code.
The code for the program is as follows:
CODE:
private static void IterateThroughList() { var theGalaxies = new List<Galaxy> { new Galaxy() { Name="Tadpole", MegaLightYears=400}, new Galaxy() { Name="Pinwheel", MegaLightYears=25}, new Galaxy() { Name="Milky Way", MegaLightYears=0}, new Galaxy() { Name="Andromeda", MegaLightYears=3} }; foreach (Galaxy theGalaxy in theGalaxies) { Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears); }
OUTPUT:
The output of the following program will be:
Tadpole 400 Pinwheel 25 Milky Way 0 Andromeda 3
Conclusion:
C# provides a wide range of collections to store and operate with groups of related objects. These collections include linked lists, queues, stacks, dictionaries, and hash sets. Every collection type has unique traits and is made to handle various circumstances and requirements.
Lists allow for adjustable sizing, while arrays are fixed-size collections that store elements sequentially. Key-value pair storage and quick lookup operations are made possible by dictionaries. Hash sets guarantee element uniqueness and provide quick insertion and removal. At both ends, linked lists offer effective insertion and removal.
You can choose the best collection for your particular needs by being aware of the characteristics and behaviors of different collections. When working with groupings of related data, C# collections offer flexibility, efficiency, and convenience. This enables you to manage and manipulate data in your applications easily.