C# Tutorial - List<T> Class

List <T> Class

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Characteristics of List <T> Class

  • The List <T> class is the generic equivalent of the ArrayList class. It implements the IList generic interface by using an array whose size is dynamically increased as required.
  • Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
  • The List <T> class uses both an equality comparer and an ordering comparer.
  • List <T> accepts null as a valid value for reference types and allows duplicate elements.
  • Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equality comparer for the list elements. The default equality comparer for type T is determined as follows. If type T implements the IEquatable <T > generic interface, then the equality comparer is the Equals(T) method of that interface; otherwise, the default equality comparer is Object.Equals(Object).
  • Methods such as BinarySearch and Sort use an ordering comparer for the list elements. The default comparer for type T is determined as follows. If type T implements the IComparable <T > generic interface, then the default comparer is the CompareTo(T) method of that interface; otherwise, if type T implements the nongeneric IComparable interface, then the default comparer is the CompareTo(Object) method of that interface. If type T implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly.

The following example demonstrates several properties and methods of the List <T> generic class of type string.


using System;
using System.Collections.Generic;


namespace ListExample
{
    class Program
    {
        static void Main(string[] args)
        {
            List CityList = new List();

            Console.WriteLine("Capacity :" + CityList.Capacity);
            CityList.Add("Udaipur");
            CityList.Add("Jaipur");
            CityList.Add("Kota");
            CityList.Add("Jodhpur");
            CityList.Add("Bhopal");

            Console.WriteLine();
            foreach (string city in CityList)
                Console.WriteLine(city);

            Console.WriteLine();


            Console.WriteLine("Capacity :" + CityList.Capacity);

            Console.WriteLine();
            Console.WriteLine("Count :" + CityList.Count);

            Console.WriteLine();

            Console.WriteLine("Contains \"Jodhpur\" :{0}",CityList.Contains("Jodhpur"));

            Console.WriteLine();

            Console.WriteLine("Insert(2,Ratlam)");

            CityList.Insert(2, "Ratlam");

            Console.WriteLine();
            foreach (string city in CityList)
                Console.WriteLine(city);

            Console.WriteLine();

            Console.WriteLine("CityList[4]: {0}", CityList[4]);

            Console.WriteLine();

            Console.WriteLine("Remove Jaipur");
            CityList.Remove("Jaipur");



            Console.WriteLine();
            foreach (string city in CityList)
                Console.WriteLine(city);

         
            CityList.TrimExcess();
            Console.WriteLine();
            Console.WriteLine("Capacity :" + CityList.Capacity);

            Console.WriteLine();
            Console.WriteLine("Count :" + CityList.Count);

            Console.WriteLine();
            Console.WriteLine("CityList After Sorted");
            CityList.Sort();

            Console.WriteLine();
         
            foreach (string city in CityList)
                Console.WriteLine(city);

            Console.WriteLine();
            Console.WriteLine("CityList After Reverse");
            CityList.Reverse();

            Console.WriteLine();

            foreach (string city in CityList)
                Console.WriteLine(city);

            CityList.Clear();

          

            Console.WriteLine();
            Console.WriteLine("Capacity :" + CityList.Capacity);

            Console.WriteLine();
            Console.WriteLine("Count :" + CityList.Count);


        }
    }
}
    


This code example produces the following output:

Capacity :0

Udaipur
Jaipur
Kota
Jodhpur
Bhopal

Capacity :8

Count :5

Contains "Jodhpur" :True

Insert(2,Ratlam)

Udaipur
Jaipur
Ratlam
Kota
Jodhpur
Bhopal

CityList[4]: Jodhpur

Remove Jaipur

Udaipur
Ratlam
Kota
Jodhpur
Bhopal

Capacity :5

Count :5

CityList After Sorted

Bhopal
Jodhpur
Kota
Ratlam
Udaipur

CityList After Reverse

Udaipur
Ratlam
Kota
Jodhpur
Bhopal

Capacity :5

Count :0

The following example demonstrates how to add, remove, and insert a simple business object in a List <T >.

using System;
using System.Collections.Generic;


namespace ListApp
{
    public class Course : IEquatable, IComparable
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
        public string Duration { get; set; }
        public int Fee { get; set; }

        public override string ToString()
        {
            return "Course Id: " + CourseId + "   Course Name: " + CourseName +"    Duration :"+ Duration +"    Fee :"+Fee;
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Course objAsCourse = obj as Course;
            if (objAsCourse == null) return false;
            else return Equals(objAsCourse);
        }
        public override int GetHashCode()
        {
            return CourseId;
        }
        public bool Equals(Course other)
        {
            if (other == null) return false;
            return (this.CourseId.Equals(other.CourseId));
        }

        // Default comparer for Course type.
        public int CompareTo(Course compareCourse)
        {
            // A null value means that this object is greater.
            if (compareCourse == null)
                return 1;

            else
                return this.CourseId.CompareTo(compareCourse.CourseId);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //Create a List of Courses
            List courses = new List();

            // Add Course to the list.

            courses.Add(new Course { CourseId = 101, CourseName = "VB.NET", Duration = "45 Days", Fee = 5000 });
            courses.Add(new Course { CourseId = 102, CourseName = "ASP.NET MVC", Duration = "60 Days", Fee = 7000 });
            courses.Add(new Course { CourseId = 103, CourseName = "VC#.NET", Duration = "45 Days", Fee = 6000 });
            courses.Add(new Course { CourseId = 104, CourseName = "PHP", Duration = "45 Days", Fee = 5000 });
            courses.Add(new Course { CourseId = 105, CourseName = "Core Java", Duration = "45 Days", Fee = 4500 });
            courses.Add(new Course { CourseId = 106, CourseName = "JAVA EE", Duration = "60 Days", Fee = 6000 });

            // Write out the courses in the list. This will call the overridden ToString method
            // in the Course class.
            Console.WriteLine("Courses List");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }

        // Check the list for part #4. This calls the IEquatable.Equals method
        // of the Part class, which checks the PartId for equality.
        Console.WriteLine("\nContains(\"104\"): {0}",
        courses.Contains(new Course { CourseId = 104, CourseName = "PHP", Duration = "45 Days", Fee = 5000 }));


            Console.WriteLine("\nCourses[3]: {0}", courses[3]);

            Console.WriteLine("\nRemove(\"104\")");

            // This will remove Course 104 even though the CourseName is different,
            // because the Equals method only checks CourseId for equality.
            courses.Remove(new Course { CourseId = 104, CourseName = "ASP" });

            Console.WriteLine("Courses List after Delete");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }

            // This will remove the part at index 3.
            courses.RemoveAt(3);

            Console.WriteLine();
            Console.WriteLine("Courses List after Delete index 3");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }
            courses.Insert(2,new Course { CourseId = 107, CourseName = "ASP.NET Web API", Duration = "60 Days", Fee = 6000 });

            Console.WriteLine("Courses List after Insert at Index 2");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }


            // Call Sort on the list. This will use the 
            // default comparer, which is the Compare method 
            // implemented on Course.
           
            courses.Sort();

            Console.WriteLine("Courses List after Sort by Course Id");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }


            courses.Reverse();
            Console.WriteLine("Courses List after Reverse");
            foreach (Course aCourse in courses)
            {
                Console.WriteLine(aCourse);
            }
        }
    }
}

Output of Above Example

Courses List
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 104   Course Name: PHP    Duration :45 Days    Fee :5000
Course Id: 105   Course Name: Core Java    Duration :45 Days    Fee :4500
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000

Contains("104"): True

Courses[3]: Course Id: 104   Course Name: PHP    Duration :45 Days    Fee :5000

Remove("104")
Courses List after Delete
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 105   Course Name: Core Java    Duration :45 Days    Fee :4500
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000

Courses List after Delete index 3
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000
Courses List after Insert at Index 2
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 107   Course Name: ASP.NET Web API    Duration :60 Days    Fee :6000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000
Courses List after Sort by Course Id
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000
Course Id: 107   Course Name: ASP.NET Web API    Duration :60 Days    Fee :6000
Courses List after Reverse
Course Id: 107   Course Name: ASP.NET Web API    Duration :60 Days    Fee :6000
Course Id: 106   Course Name: JAVA EE    Duration :60 Days    Fee :6000
Course Id: 103   Course Name: VC#.NET    Duration :45 Days    Fee :6000
Course Id: 102   Course Name: ASP.NET MVC    Duration :60 Days    Fee :7000
Course Id: 101   Course Name: VB.NET    Duration :45 Days    Fee :5000

Reference:

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2