List.md - brainchildservices/curriculum GitHub Wiki

Slide 1

C# | List Class

The List is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list.
It is the generic version of the ArrayList that comes under System.Collection.Generic namespace.

  • List equivalent of the ArrayList, which implements IList.
  • It comes under System.Collections.Generic namespace.
  • List can contain elements of the specified type. It provides compile-time type checking and doesn't perform boxing-unboxing because it is generic.
  • If the Count becomes equals to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element
  • List class is not sorted by default and elements are accessed by zero-based index.

Slide 2

How to create a List?

  • System.Collections.Generic namespace must added to access the List class..

  • List can be created using the new keyword and List class where T is the type of the object that can be stored in the List.

  • Since it's a Generic Collection, we need to specify the data type the elements in angle brackets after List.

  • List can be created as an empty constructor or with an integer value as argument to the constructor which becomes the capacity of the constructor.

  • If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array.

  • If the Count becomes equals to Capacity, then the capacity of the List increased automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element
    List<T> listName = new List<T>();
    Or
    List<T> listName = new List<T>(someIntegerValue);

    using System;
    using System.Collections.Generic; 			//Adding Collections.Generic Namespace for using List  
    
      			
    public class Program
    {
        public static void Main()
        {
            List<int> intgerList=new List<int>();	//Creating a List that can store integer values. The size of the List is not specified
      
            List<string> stringList=new List<string>(10);    //Creating a List that can store string values. The initial size of the List is set to 10
        }
    }
    

Slide 3

How to add items to a C# List?

  • Using Add method: The Add method adds an element to a List.

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);					//Adding integer values to List: intgerList
            intgerList.Add(20);
            intgerList.Add(30);
      
            List<string> stringList = new List<string>(10);
      
            stringList.Add("John");					//Adding string values to List: stringList
            stringList.Add("Toby");
            stringList.Add("Felix");
        }
    }
    

Slide 4

  • Add a collection to a List. The AddRange method is used to add a collection to a List. ListName.AddRange(nameOfTheCollection);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            int[] intArr = new int[]{40, 50, 60}; 		//Creating a integer array that can be added to the integer list using AddRange Method
      
            List<int> intgerList = new List<int>();
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
      
            intgerList.AddRange(intArr); 			//Adding the intger array to the intgerList using the AddRange Method
      
            string[] stringArr = new string[]{"Kevin", "Philip"}; 	//Creating a string array that can be added to the string list using AddRange Method
      
            List<string> stringList = new List<string>(10);
      
            stringList.Add("John");
            stringList.Add("Toby");
            stringList.Add("Felix");
      
            stringList.AddRange(stringArr);				//Adding the string array to the stringList using the AddRange Method
        }
    } 
    

Slide 5

How to count the number of items in List?

The number of elements in a List can be counted using the List.Count property.
Count: Gets the number of elements actually contained in the List.

  using System;
  using System.Collections.Generic;

  public class Program
  {
      public static void Main()
      {
	      int[] intArr = new int[]{40, 50, 60}; 					
	
	      List<int> intgerList = new List<int>();
	      intgerList.Add(10);
	      intgerList.Add(20);
	      intgerList.Add(30);
	
	      intgerList.AddRange(intArr); 							
	
	      string[] stringArr = new string[]{"Kevin", "Philip"}; 	
	
	      List<string> stringList = new List<string>(10);
	
	      stringList.Add("John");
	      stringList.Add("Toby");
	      stringList.Add("Felix");
	
	      stringList.AddRange(stringArr);							
	
	      Console.WriteLine(stringList.Count);		//Using Count method to check the number of elements in the List.
      }
  } 

Slide 6

How to find the capacity of the List?

The capacity of the List can be found using the List.Capacity property.
Capacity: Number of elements List can contain. The default capacity of a List is 0.

  using System;
  using System.Collections.Generic;

  public class Program
  {
      public static void Main()
      {
	      int[] intArr = new int[]{40, 50, 60}; 					
	
	      List<int> intgerList = new List<int>();
	      intgerList.Add(10);
	      intgerList.Add(20);
	      intgerList.Add(30);
	
	      intgerList.AddRange(intArr); 							
	
	      string[] stringArr = new string[]{"Kevin", "Philip"}; 	
	
	      List<string> stringList = new List<string>(10);
	
	      stringList.Add("John");
	      stringList.Add("Toby");
	      stringList.Add("Felix");
	
	      stringList.AddRange(stringArr);							
	
	      Console.WriteLine("The capacity of the string List is: "+ stringList.Capacity);	//Using Capacity method to check the number of elements the List can store
	
	      Console.WriteLine("The capacity of the integer List is: "+ intgerList.Capacity);	//Using Capacity method to check the number of elements the List can store
      }
  }

Slide 7

How to access/read elements in a List?

  • Elements of the List can be accessed using the [] and the index .
    ListName[index];

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            int[] intArr = new int[]{40, 50, 60};
      
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
      
            intgerList.AddRange(intArr);
      
            Console.WriteLine("Element at index 1 is: " + intgerList[1]);		//Accessing the value using the [index] operation
      
            Console.WriteLine("Element at index 5 is: " + intgerList[5]);
        }
    }
    

Slide 8

  • Interating through the List:
  1. By generalizing:

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
       public static void Main()
       {
           int[] intArr = new int[]{40, 50, 60};
     
           List<int> intgerList = new List<int>();
     
           intgerList.Add(10);
           intgerList.Add(20);
           intgerList.Add(30);
     
           intgerList.AddRange(intArr);
     
           foreach(var item in intgerList)
           {
     	      Console.Write(item +" ");
           }
       }
    

    }

Slide 9

  1. By specifying the exact datatype:

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
       public static void Main()
       {
           int[] intArr = new int[]{40, 50, 60};
     
           List<int> intgerList = new List<int>();
     
           intgerList.Add(10);
           intgerList.Add(20);
           intgerList.Add(30);
     
           intgerList.AddRange(intArr);
     
           foreach(int item in intgerList)			//foreach to iterate through the List
           {
     	      Console.Write(item +" ");
           }
       }
    

    }

Slide 10

How to insert elements at a position in a C# List?

  • The Insert method of List class inserts an object at a given position. The first parameter of the method is the 0th based index in the List.

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            int[] intArr = new int[]{40, 50, 60};
      
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
      
            intgerList.AddRange(intArr);
      
            Console.WriteLine("====================Original List============");
    
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
            intgerList.Insert(3,35);		//Inserting 35 at index 3
      
            Console.WriteLine("\n====================Modified List============");
      
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
    
        }
    }
    

Slide 11

  • The InsertRange method can insert a collection at the given position.

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            int[] intArr = new int[]{40, 50, 60};
      
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
      
            intgerList.AddRange(intArr);
      
            Console.WriteLine("====================Original List============");
    
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
            intgerList.InsertRange(1,intArr);		//Inserting the intArr collection at index 1
      
            Console.WriteLine("\n====================Modified List============");
      
            foreach(int item in intgerList)					
            {
      	Console.Write(item +" ");
            }
      
        }
    }
    

Slide 12

How to remove an item from a List

  • Remove
    The Remove method removes the first occurrence of the given item in the List.
    ListName.Remove(SomeValue);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
    
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
            intgerList.Add(30);
            intgerList.Add(20);
            intgerList.Add(25);
            intgerList.Add(40);
            intgerList.Add(30);
      
            Console.WriteLine("====================Original List============");
    
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
            intgerList.Remove(30);			//Removes the first occurance of 30 from the List
      
            Console.WriteLine("\n====================Modified List============");
      
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
        }
    }
    

Slide 13

  • RemoveAt
    The RemoveAt method removes an item at the given position
    ListName.Remove(SomeIndex);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
    
            List<int> intgerList = new List<int>();
      
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
            intgerList.Add(30);
            intgerList.Add(20);
            intgerList.Add(25);
            intgerList.Add(40);
            intgerList.Add(30);
      
      
            Console.WriteLine("====================Original List============");
    
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
            intgerList.RemoveAt(0);			//Removes the element at index 0
      
            Console.WriteLine("\n====================Modified List============");
      
            foreach(int item in intgerList)					
            {
      	      Console.Write(item +" ");
            }
      
        }
    }  
    

Slide 14

  • RemoveRange
    The RemoveRange method removes a list of items from the starting index to the number of items
    ListName.RemoveAt(SomeIndex, Count);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<int> intgerList = new List<int>();
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
            intgerList.Add(30);
            intgerList.Add(20);
            intgerList.Add(25);
            intgerList.Add(40);
            intgerList.Add(30);
      
            Console.WriteLine("====================Original List============");
            foreach (int item in intgerList)
            {
      	      Console.Write(item + " ");
            }
    
            intgerList.RemoveRange(1, 4); //Removes the elements from starting index 1 to 4
      
            Console.WriteLine("\n====================Modified List============");
            foreach (int item in intgerList)
            {
      	      Console.Write(item + " ");
            }
        }
    }
    

Slide 15

  • Clear
    The Clear method of List removes all elements from the List.
    ListName.Clear();

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<int> intgerList = new List<int>();
            intgerList.Add(10);
            intgerList.Add(20);
            intgerList.Add(30);
            intgerList.Add(30);
            intgerList.Add(20);
            intgerList.Add(25);
            intgerList.Add(40);
            intgerList.Add(30);
      
            Console.WriteLine("====================Original List============");
            foreach (int item in intgerList)
            {
      	      Console.Write(item + " ");
            }
    
            intgerList.Clear(); 				//Removes all elements of the List
      
            Console.WriteLine("\n====================Modified List============");
            foreach (int item in intgerList)
            {
      	      Console.Write(item + " ");
            }
        }
    }
    

Slide 16

How to find an element in a C# List?

The IndexOf method finds an item in a List. The IndexOf method returns -1 if there are no items found in the List.

  • IndexOf with one parameter(item to be searched), to search from start to end
    ListName.IndexOf(ValueToBeSearched);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<string> nameList = new List<string>();
      
            nameList.Add("Zerin");
            nameList.Add("Jacob");
            nameList.Add("Preety");
            nameList.Add("Amal");
            nameList.Add("Chris");
            nameList.Add("Ravi");
            nameList.Add("Evan");
      
            int location = nameList.IndexOf("Jacob"); 				//Using IndexOf to find the index of name Zerin
      
            if (location >= 0)
            {
      	      Console.WriteLine("The person was found at index: " + location);
            }
            else
      	      Console.WriteLine("Person not found");
        }
    }
    

Slide 16 Downwards

  using System;
  using System.Collections.Generic;

  public class Program
  {
      public static void Main()
      {
	      List<string> nameList = new List<string>();
	
	      nameList.Add("Zerin");
	      nameList.Add("Jacob");
	      nameList.Add("Preety");
	      nameList.Add("Amal");
	      nameList.Add("Chris");
	      nameList.Add("Ravi");
	      nameList.Add("Evan");
	
	      int location = nameList.IndexOf("Bob"); 				//Using IndexOf to find the index of name Bo which doesn't exist
	
	      if (location >= 0)
	      {
		      Console.WriteLine("The person was found at index: " + location);
	      }
	      else
		      Console.WriteLine("Person not found");
      }
  } 

Slide 17

  • IndexOf with two parameters: Item to be searched as well as the index where the search should start.
    ListName.IndexOf(ValueToBeSearched, IndexWhereSearchShouldStart);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<string> nameList = new List<string>();
      
            nameList.Add("Zerin");
            nameList.Add("Jacob");
            nameList.Add("Preety");
            nameList.Add("Amal");
            nameList.Add("Chris");
            nameList.Add("Ravi");
            nameList.Add("Evan");
      
            int location = nameList.IndexOf("Ravi",2); 	//Using IndexOf with index where the search should start
      
            if (location >= 0)
            {
      	      Console.WriteLine("The person was found at index: " + location);
            }
            else
      	      Console.WriteLine("Person not found");
        }
    }  
    

Slide 18

  • The LastIndexOf method finds an item from the end of List.
    ListName.LastIndexOf(ValueToBeSearched);

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            List<string> nameList = new List<string>();
      
            nameList.Add("Zerin");
            nameList.Add("Jacob");
            nameList.Add("Preety");
            nameList.Add("Amal");
            nameList.Add("Chris");
            nameList.Add("Jacob");
            nameList.Add("Evan");
      
            int location = nameList.LastIndexOf("Jacob"); 		//Using LastIndexOf to search from the end.
      
            if (location >= 0)
            {
      	      Console.WriteLine("The person was found at index: " + location);
            }
            else
      	      Console.WriteLine("Person not found");
        }
    }
    

Slide 19

How to sort a C# List elements?
The Sort method of List sorts all items of the List using the QuickSort algorithm.
ListName.Sort();

  using System;
  using System.Collections.Generic;

  public class Program
  {
      public static void Main()
      {
	      List<string> nameList = new List<string>();
	
	      nameList.Add("Zerin");
	      nameList.Add("Jacob");
	      nameList.Add("Preety");
	      nameList.Add("Amal");
	      nameList.Add("Chris");
	      nameList.Add("Ravi");
	      nameList.Add("Evan");
	
	      Console.WriteLine("====================Original List============");
	
	      foreach (string item in nameList)
	      {
		      Console.Write(item + ", ");
	      }

	      nameList.Sort();
	
	      Console.WriteLine("\n\n====================Modified List============");
	
	      foreach (string item in nameList)
	      {
		      Console.Write(item + ", ");
	      }
      }
  }

Slide 20

How to reverse a C# List elements?

The Reverse method of List reverses the order all items in the List.
ListName.Reverse();

  using System;
  using System.Collections.Generic;

  public class Program
  {
      public static void Main()
      {
	      List<string> nameList = new List<string>();
	
	      nameList.Add("Zerin");
	      nameList.Add("Jacob");
	      nameList.Add("Preety");
	      nameList.Add("Amal");
	      nameList.Add("Chris");
	      nameList.Add("Ravi");
	      nameList.Add("Evan");
	
	      Console.WriteLine("====================Original List============");
	
	      foreach (string item in nameList)
	      {
		      Console.Write(item + ", ");
	      }

	      nameList.Reverse();
	
	      Console.WriteLine("\n\n====================Modified List============");
	
	      foreach (string item in nameList)
	      {
		      Console.Write(item + ", ");
	      }
      }
  } 

Slide 21

Creating a User Defined List of objects

  • We are going to create a class Author.
    Author has properties: name(string), age(short), title(string), mvp(bool), pubdate(DateTime):
    Author has parameterized Constructor to get values for all the properties.

    using System;
    
    public class Author					//Creating class with required properties and Constructor
    {
        public string Name { get; set; }
        public short Age { get; set; }
        public string BookTitle { get; set; }
        public bool IsMVP { get; set; }
        public DateTime PublishedDate { get; set; }
    
        public Author(string name, short age, string title, bool mvp, DateTime pubdate)
        {
            Name = name;
            Age = age;
            BookTitle = title;
            IsMVP = mvp;
            PublishedDate = pubdate;
        }
    }
    
    public class Program
    {
        public static void Main()
        {
      
        }
    } 
    

Slide 22

  • Adding using System.Collections.Generic; namespace
    Creating a List of Authors in Main method

    using System;
    using System.Collections.Generic;				//Adding System.Collections.Generic namespace
    
    public class Author								
    {
        public string Name	{ get; set; }
        public short Age	{ get; set; }
        public string BookTitle	{ get; set; }
        public bool IsMVP	{ get; set; }
        public DateTime PublishedDate	{ get; set; }
    
        public Author(string name, short age, string title, bool mvp, DateTime pubdate)
        {
            Name = name;
            Age = age;
            BookTitle = title;
            IsMVP = mvp;
            PublishedDate = pubdate;
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            List<Author> AuthorList=new List<Author>();		//Created a List that stores Author object
        }
    } 
    

Slide 23

  • Creating object of Author with the arguments for the Constructor Parameter
    And adding the created object to the List

    using System;
    using System.Collections.Generic;
    
    public class Author
    {
        public string Name { get; set; }
        public short Age { get; set; }
        public string BookTitle { get; set; }
        public bool IsMVP { get; set; }
        public DateTime PublishedDate { get; set; }
    
        public Author(string name, short age, string title, bool mvp, DateTime pubdate)
        {
            Name = name;
            Age = age;
            BookTitle = title;
            IsMVP = mvp;
            PublishedDate = pubdate;
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            List<Author> AuthorList = new List<Author>();
      
            //Creating an object of Author
            Author Author1 = new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003, 7, 10));
      
            //Adding the created object to the AuthorList
            AuthorList.Add(Author1);
        }
    }
    

Slide 24

Instead of creating object and then adding it to the List, this can be done in a single step.
The right side of object creation goes inside the Add method.

  using System;
  using System.Collections.Generic;

  public class Author
  {
      public string Name { get; set; }
      public short Age { get; set; }
      public string BookTitle { get; set; }
      public bool IsMVP { get; set; }
      public DateTime PublishedDate { get; set; }

      public Author(string name, short age, string title, bool mvp, DateTime pubdate)
      {
	      Name = name;
	      Age = age;
	      BookTitle = title;
	      IsMVP = mvp;
	      PublishedDate = pubdate;
      }
  }

  public class Program
  {
      public static void Main()
      {
	      List<Author> AuthorList = new List<Author>();
	
	      //Creating an object of Author
	      //Author Author1 = new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003, 7, 10));
	
	      //New Object becomes the paramater for the Add method
	      AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003, 7, 10)));
      }
  } 

Slide 25

Adding other objects to the List.

  using System;
  using System.Collections.Generic;

  public class Author
  {
      public string Name { get; set; }
      public short Age { get; set; }
      public string BookTitle { get; set; }
      public bool IsMVP { get; set; }
      public DateTime PublishedDate { get; set; }

      public Author(string name, short age, string title, bool mvp, DateTime pubdate)
      {
	      Name = name;
	      Age = age;
	      BookTitle = title;
	      IsMVP = mvp;
	      PublishedDate = pubdate;
      }
  }

  public class Program
  {
      public static void Main()
      {
	      List<Author> AuthorList = new List<Author>();
	
	      //Adding all objects to the AuthorList
	      AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003, 7, 10)));
	      AuthorList.Add(new Author("Neel Beniwal", 18, "Graphics Development with C#", false, new DateTime(2010, 2, 22)));
	      AuthorList.Add(new Author("Praveen Kumar", 28, "Mastering WCF", true, new DateTime(2012, 01, 01)));
	      AuthorList.Add(new Author("Mahesh Chand", 35, "Graphics Programming with GDI+", true, new DateTime(2008, 01, 20)));
	      AuthorList.Add(new Author("Raj Kumar", 30, "Building Creative Systems", false, new DateTime(2011, 6, 3)));
	
      }
  }

Slide 26

  • Iterating through the List to print all the items in the List

    using System;
    using System.Collections.Generic;
    
    public class Author
    {
        public string Name { get; set; }
        public short Age { get; set; }
        public string BookTitle { get; set; }
        public bool IsMVP { get; set; }
        public DateTime PublishedDate { get; set; }
    
        public Author(string name, short age, string title, bool mvp, DateTime pubdate)
        {
            Name = name;
            Age = age;
            BookTitle = title;
            IsMVP = mvp;
            PublishedDate = pubdate;
        }
    }
    
    public class Program
    {
        public static void Main()
        {
            List<Author> AuthorList = new List<Author>();
      
            AuthorList.Add(new Author("Mahesh Chand", 35, "A Prorammer's Guide to ADO.NET", true, new DateTime(2003, 7, 10)));
            AuthorList.Add(new Author("Neel Beniwal", 18, "Graphics Development with C#", false, new DateTime(2010, 2, 22)));
            AuthorList.Add(new Author("Praveen Kumar", 28, "Mastering WCF", true, new DateTime(2012, 01, 01)));
            AuthorList.Add(new Author("Mahesh Chand", 35, "Graphics Programming with GDI+", true, new DateTime(2008, 01, 20)));
            AuthorList.Add(new Author("Raj Kumar", 30, "Building Creative Systems", false, new DateTime(2011, 6, 3)));
      
            //Iterating through the List to print all details.
            foreach (var author in AuthorList)
            {
      	      Console.WriteLine("Author: {0},{1},{2},{3},{4}", author.Name, author.Age, author.BookTitle, author.IsMVP, author.PublishedDate);
            }
        }
    } 
    

Slide 27

Exercise:

  1. Write a program to create a List of class Employee.
    Employee class has properties: Name(string), age(short), Identity(int) , DOB(DateTime), Designation(string)
    Create a List of employees, Add new employees, View all employess, Insert an Employee at index 2, View updated Employee List, Remove some Employees and View updated Employee List

  2. Write a program to create a List of class Student.
    Studentclass has properties: Name(string), age(short), Marks(int) , grade(char)
    Create a List of Student, Add new Students, View all Students, Insert a Student at index 3, View updated Student List, Remove some Students and View updated Student List

References:
https://www.c-sharpcorner.com/article/c-sharp-list/
https://www.geeksforgeeks.org/c-sharp-list-class/
https://www.tutorialsteacher.com/csharp/csharp-list
https://www.c-sharpcorner.com/UploadFile/mahesh/create-a-list-of-objects-in-C-Sharp/
https://www.youtube.com/watch?v=MQXOuYk8qtg&list=PLVlQHNRLflP8DCUdve6NEAfu8T6M9127i&index=5

⚠️ **GitHub.com Fallback** ⚠️