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#

List Implementation in C#

In C# programming, a generic collection is known to as a "list" and is used to store elements or objects in the form of a System. Collection.Common namespace. A list and an array list will do the same tasks. However, a list is a generic collection, an array list is not a generic collection. The List's size varies based on demand because it is dynamic.

Important Points:

  • The ICollection<T>, IEnumerable<T>, IList<T>, IReadOnlyCollection<T>, and IReadOnlyList<T> interfaces are all implemented by the List class together with the ICollection, IEnumerable, and IList interfaces.
  • It supports null as a valid value for reference types and allows for the duplication of items.
  • The List's Capacity is automatically expanded by reallocating the internal array if the Count reaches the Capacity.
  • The List's elements are not automatically sorted. Instead, they are retrieved using zero-based indexes.

Let's create a list:

Step 1:

System.Collection.Generic namespace is included. And also it will utilize the generics namespace in your program by using a keyword.

Step 2:

Using the List <T> class create a list.

Step 3:

List<T> class offers two alternative methods for adding elements to your List and the techniques.

NOTE: Additionally, you can add by using collection initializers. As shown in the below example:

Example:

// Creating List using List class

// and Adding elements using the

//Collection initializers

List<string> my_list1 = new List<string>() { “Java”, “Java123”, “Javatpoint” };

Step 4:

Use one of the following approaches to access the List elements:

  • Using the for-each loop: Use the foreach loop to access the items and elements of the List.
  • Using ForEach()method: The specified action is carried out on each element of the <ListT> using this method.
  • Using Indexers: Indexers can access the List's objects and items.

Example:

Program:

The following program is as follows:

// C# program to illustrate how

// to create a list

using System;

using System.Collections.Generic;

class Preethi {

            // Main Method

            static public void Main()

            {

                        // Creating a list using the List class

                        // and List<T>() Constructor

                        List<int> my_list = new List<int>();

                        // Adding elements to List

                        // Using Add() method

                        my_list.Add(1);

                        my_list.Add(10);

                        my_list.Add(100);

                        my_list.Add(1000);

                        my_list.Add(10000);

                        my_list.Add(100000);

                        my_list.Add(1000000);

                        // Accessing elements of my_list

                        // Using foreach loop

                        foreach(int a in my_list)

                        {

                                    Console.WriteLine(a);

                        }

            }

}

OUTPUT:

The Output for the following program will be:

List Implementation in C#

Example:

Program:

The following program is as follows:

using System;

using System.Collections.Generic;

class Program

{

    static void Main()

    {

        // Creating a list of integers

        List<int> numbers = new List<int>();

        // Adding elements to the List

        numbers.Add(10);

        numbers.Add(20);

        numbers.Add(30);

        // Accessing elements by index

        int firstNumber = numbers[0];  // 10

        int secondNumber = numbers[1]; // 20

        // Modifying an element

        numbers[2] = 40;

        // Removing an element

        numbers.Remove(20);

        // Iterating over the List

        foreach (int number in numbers)

        {

            Console.WriteLine(number);

        }

    }

}

OUTPUT:

The Output for the following program will be:

List Implementation in C#

In previously mentioned example, we build a List<int> called numbers and add three integers. We can access and alter elements according to their index by using the square bracket notation ([]). We can also delete components based on their value using the delete method. The List and Output of each element are then examined using a for each loop.

To make a list of objects of that type, swap out int with any other valid C# type.

Example:

Program:

The following program is as follows:

// C# program to illustrate how

// to remove objects from the List

using System;

using System.Collections.Generic;

class Preethi {

            // Main Method

            static public void Main()

            {

                        // Creating a list using the List class

                        // and List<T>() Constructor

                        List<int> my_list = new List<int>();

                        // Adding elements to List

                        // Using Add() method

                        my_list.Add(1);

                        my_list.Add(10);

                        my_list.Add(100);

                        my_list.Add(1000);

                        my_list.Add(10000);

                        my_list.Add(100000);

                        my_list.Add(1000000);

                        my_list.Add(10000000);

                        my_list.Add(100000000);

                        // Initial Count

                        Console.WriteLine("Initial count:{0}", my_list.Count);

                        // After using Remove() method

                        my_list.Remove(10);

                        Console.WriteLine("2nd count:{0}", my_list.Count);

                        // After using RemoveAt() method

                        my_list.RemoveAt(4);

                        Console.WriteLine("3rd count:{0}", my_list.Count);

                        // After using RemoveRange() method

                        my_list.RemoveRange(0, 2);

                        Console.WriteLine("4th count:{0}", my_list.Count);

                        // After using Clear() method

                        my_list.Clear();

                        Console.WriteLine("5th count:{0}", my_list.Count);

            }

}

OUTPUT:

The Output for the following program will be:

List Implementation in C#

How to sort a list?

This method compares list elements using a given IComparer<T> implementation or a specific or default IComparer<T> implementation. It sorts all or some of the elements in the List<T>.

Example:

Program:

The following program is as follows:

// C# program to illustrate how

//Sort a list

using System;

using System.Collections.Generic;

class Preethi {

            // Main Method

            static public void Main()

            {

                        // Creating a list using the List class

                        // and List<T>() Constructor

                        List<int> my_list = new List<int>();

                        // Adding elements to List

                        // Using Add() method

                        my_list.Add(496);

                        my_list.Add(1000);

                        my_list.Add(100);

                        my_list.Add(10);

                        my_list.Add(10000);

                        my_list.Add(10000000);

                        my_list.Add(1000000);

                        my_list.Add(100000);

                        my_list.Add(0000);

                        // Without Sorted List

                        Console.WriteLine("UnSorted List:");

                        foreach(int a in my_list)

                        {

                                    Console.WriteLine(a);

                        }

                        // After Sort method

                        my_list.Sort();

                        Console.WriteLine("Sorted List:");

                        foreach(int a in my_list)

                        {

                                    Console.WriteLine(a);

                        }

            }

}

OUTPUT:

The Output for the following program will be:

List Implementation in C#

How to create a List?

Using the List <T> constructor accepts an int-type argument representing the List's Capacity; we can create a list. If we don't provide the Capacity, the list size will be dynamic every time a new element is added.

The list size will automatically increase if the capacity value is used when creating the List and more entries are added than the defined Capacity allows.

How to remove elements from the List?

The following methods will be provided by the List <T> class and it can be used to remove list elements:

  • Remove(T): This method removes an object's initial occurrence from a list.
  • RemoveAll(Predicate<T>): This method removes all the elements that satisfy, and its predicate's requirements are eliminated.
  • Clear(): The List<T> can have all of its elements removed by using the Clear() method.

Adding elements to the List:

After creating a list, we can add things later. And methods are:

1. Create List:

    List<int> lst = new List<int>

    {

        1,2,3,4,5,6

    };

    2. Add items after creating a list:

    List<int> lst = new List<int>();

    lst.Add(1);

    lst.Add(2);

    lst.Add(3);

    lst.Add(4);

    lst.Add(5);

    lst.Add(3);

    Properties of a list:

    Two properties included in the List are:

    1. Capacity

    2. Count

    Read all elements of a list:

    We must loop around a list to get all its components. We have to use for or for each loop to obtain the elements. The code for collecting all the items utilizing both loops and printing the values of the elements is shown below:

    1. Using a foreach loop:

    foreach (var item in lst)

    {

        Console.WriteLine(item);

    }

    2. Using for loop:

    The loop in this method must continue until the last element in the List. To do it, I used the List's Count property.

    for (int i = 0; i < lst.Count; i++)

    {

        Console.WriteLine(lst[i]);

    }

    From both the methods, the result will be the same. I'm using the example from the previous List. And the result is:

    OUTPUT:

    1

    2

    3

    4

    5

    3

    Remove elements from a list:

    We can use several list methods to remove items from a list.

    1. Remove(T item): The first instance of an element in a list is removed by using this procedure.

    lst.Remove(3); // Removes the first occurrence of element 3

    2. RemoveAll(Predicate<T> match): This method removes all elements from a list that match the condition by defining the predicate. The predicate is a required parameter.

    lst.RemoveAll(x=>x==3); // Removes all the elements 3

    3. RemoveAt(int index): This procedure removes The element from the specified index. The index must be provided as a parameter.

    lst.RemoveAt(0); // Removes 0th index element from a list

    4. RemoveRange(int index, int count): This procedure removes the element from the specified Count to the given index. The initial index and Count must be supplied as parameters.

    lst.RemoveRange(0,2); // Removes element 1,2 because the starting index is 0 and Count is 2

    5. Clear(): All list elements are removed with this method.

    Methods of List in C# with examples:

    The following list class methods are as follows:

    1. Add(T): The List's end can have an object added using this technique. A reference type may have a null value added to it.

    Example:

    Program:

    The following program will be:

    using System;

    using System.Collections.Generic;

    public class ListDemo

    {

    public static void Main()

    {

    List<int> lstNum = new List<int>(){1, 2, 3, 4};

    //Adding 5 at the end of the List

    sternum.Add(5);

    foreach(int num in lstNum)

    {

    Console.WriteLine(num);

    }

    }

    }

    OUTPUT:

    The Output for the following program will be:

    List Implementation in C#

    2. Clear(): To eliminate every element from the List, apply this method.

    3. Insert( Int32, T ): A specific location may be added to the list using this method.

    Example:

    Program:

    The following program will be:

    using System;

    using System.Collections.Generic;

    public class ListDemo

    {

    public static void Main()

    {

    List<string> lstCities = new List <string>(){"Mumbai", "Pune", "Bengaluru"};

    //inserting element at third position

    lstCities.Insert(2, "Chennai");

    foreach(string city in lstCities)

    {

    Console.WriteLine(city);

    }

    }

    }

    OUTPUT:

    The Output for the following program will be:

    List Implementation in C#

    4. RemoveAt( Int32 ): Using this method, a list item at the specified position is removed.

    5. Sort(): The List's elements are sorted using this method's default comparer.

    Example:

    Program:

    The following program will be:

    using System;

    using System.Collections.Generic;

    public class ListDemo

    {

    public static void Main()

    {

    List<string> lstCities = new List <string>(){"Mumbai","Pune","Bengaluru"};

    Console.WriteLine("Initial list values");

    foreach(string city in lstCities)

    {

    Console.WriteLine(city);

    }

    //sorting elements in ascending order

    lstCities.Sort();

    Console.WriteLine("\nList after sorting in ascending order");

    foreach(string city in lstCities)

    {

    Console.WriteLine(city);

    }

    //sorting elements in descending order by calling Reverse()

    lstCities.Reverse();

    Console.WriteLine("\nList after sorting in descending order");

    foreach(string city in lstCities)

    {

    Console.WriteLine(city);

    }

    }

    }

    OUTPUT:

    The Output for the following program will be:

    List Implementation in C#

    The List was sorted using Sort() in the program as mentioned above's first step to ascending order. The Reverse() function was then used on the sorted List to sort it in descending order. We must implement an IComparable interface or use LINQ to sort a list of custom objects. We may sort a list of int, string, and other types using the Sort() method. As shown in the example below, we can arrange this kind of List in another method:

    Conclusion:

    A list is a dynamic data structure in C# that enables elements in addition, removal, and index access.

    • The built-in List class in C# is the most popular list creation method. It offers a general list that can hold components of any type. Along with other practical techniques like sorting and searching, it supports adding, deleting, and accessing elements by index.
    • Using an array - Due to the array's predetermined size at development, this method is less flexible than List<T>. The array must be enlarged in order to add or remove elements, which can be unpleasant.
    • Making a unique list class: Making a unique class that implements a list is another choice. While requiring more programming work, this approach provides greater customization and flexibility.

    Overall, the implementation option will be determined by the program's unique requirements, such as the expected length of the List, the frequency of adding and removing components.