C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

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.

← Prev Next →