Article

Lists


C# List class is used to store and fetch elements. It can also have duplicate elements. It is found in System.Collections.Generic namespace. List class in C# represents a strongly typed list of objects. List provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List, T is the type of object. What is the ‘T’ in List? List class represents a strongly typed list of objects. List provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List, T is the type of objects. How to create List in C#? List is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List class. using System.Collections.Generic; The List is a generic collection, so you need to specify a type parameter for the type of data it can store

The following example shows how to create a integer type list and add elements in list.


using System;
using System.Collections.Generic;


public class Program
{
	public static void Main()
	{
		// adding elements using add() method
		List Numbers = new List();
		Numbers.Add(1);
		Numbers.Add(2);
		Numbers.Add(3);
		Numbers.Add(4);
		
			   foreach(var i in Numbers)
			   {
				  Console.WriteLine("First number : " +  i);
			   }
	}
}
 

Output


First number : 1
First number : 2
First number : 3
First number : 4
 

The following example shows how to create a string type list and add elements in list.


using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		// adding elements using add() method
			var cities = new List();
			cities.Add("Yamuna Nagar");
			cities.Add("Kurukshetra");
			cities.Add("Panipat");
			cities.Add("Ambala");
		
			   foreach(var i in cities)
			   {
				  Console.WriteLine("City Name: " +  i);
			   }
	}
} 

Output


City Name: Yamuna Nagar
City Name: Kurukshetra
City Name: Panipat
City Name: Ambala
 

The following example shows how to adding elements using collection initializer syntax


using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		// adding elements using collection initializer syntax
		var cities = new List() {"Kurukshetra", "Panipat", "Ambala", "Yamuna Nagar"};
			   foreach(var i in cities)
			   {
				  Console.WriteLine("City Name: " +  i);
			   }
	}

} 

Output


City Name: Kurukshetra
City Name: Panipat
City Name: Ambala
City Name: Yamuna Nagar
 

The following example shows how to adding elements into list using classe


using System;
using System.Collections.Generic;
public class Program
{
	public static void Main()
	{
		var students = new List() { 
                new Student(){ Id = 1, Name="Shubham"},
                new Student(){ Id = 2, Name="mohit"},
                new Student(){ Id = 3, Name="Rohan"},
                new Student(){ Id = 4, Name="Rahul"}
            };
	
			foreach(var name in students)
			{
				Console.WriteLine("Student Name: " + name.Name);
			}
		
	}
}

class Student{
	public int Id { get; set; }
	public string Name { get; set; }
}
 

Output


Student Name: Shubham
Student Name: mohit
Student Name: Rohan
Student Name: Rahul
 

In the above example, List Numbers = new List(); creates a list of int type. In the same way, cities are string type list. You can then add elements in a list using the Add() method or the collection-initializer syntax. You can also add elements of the custom classes using the collection-initializer syntax. The following adds objects of the Student class in the List.

Example: Add Custom Class Objects in List


                var students = new List() { 
                new Student(){ Id = 1, Name="Shubham"},
                new Student(){ Id = 2, Name="mohit"},
                new Student(){ Id = 3, Name="Rohan"},
                new Student(){ Id = 4, Name="Rahul"}
 
collection)

Example: Add Arrays in List


using System;
using System.Collections.Generic;

public class Program
{
	public static void Main()
	{
		string[] cities = new string[3]{ "Kurukshetra", "Panipat", "Ambala" };

			var popularCities = new List();

			// adding an array in a List
			popularCities.AddRange(cities);

			var favouriteCities = new List();

			// adding a List 
			favouriteCities.AddRange(popularCities);
		
			foreach(var i in favouriteCities)
			  {
				  Console.WriteLine("City Name: " +  i);
			  }
	}

}	   
 

Output


City Name: Kurukshetra
City Name: Panipat
City Name: Ambala
 

Accessing a List using LINQ The List implements the IEnumerable interface. So, we can query a list using LINQ query syntax or method syntax, as shown below.

Example: LINQ Query on List


using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
	public static void Main()
	{
		var students = new List() { 
                new Student(){ Id = 1, Name="shubham" },
                new Student(){ Id = 2, Name="rahul" },
                new Student(){ Id = 3, Name="abir" },
                new Student(){ Id = 4, Name="shubham" },
				new Student(){ Id = 5, Name="mohit" }
		};
		
		//get all students whose name is shubham
		var Student = from s in students
			where s.Name == "shubham"
			select s;
		
		foreach(var student in Student)
			Console.WriteLine("student Id " + student.Id + " , student Name " +student.Name);
	}
}

public class Student
{ 
	public int Id { get; set; }
	public string Name { get; set; }
}
 

Output


City Name: Kurukshetra
City Name: Panipat
City Name: Ambala
 

Insert Elements in List Use the Insert() method inserts an element into the List collection at the specified index. Insert() signature:void Insert(int index, T item);

Example: Insert elements into List


using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		List numbers = new List(){ 1,  3, 4 };

		numbers.Insert(1, 2);// inserts 11 at 1st index: after 10.
		
		foreach (var num in numbers)
			Console.WriteLine(num);
	}
}
 

Output


1
2
3
4
 

Remove Elements from List Use the Remove() method to remove the first occurrence of the specified element in the List collection. Use the RemoveAt() method to remove an element from the specified index. If no element at the specified index, then the ArgumentOutOfRangeException will be thrown. Remove() signature: bool Remove(T item) RemoveAt() signature: void RemoveAt(int index)

Example: Remove elements from List


using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		var numbers = new List(){ 1, 2, 3, 4, 5 };

		numbers.Remove(5); // removes 5 elements from a list
		
		numbers.RemoveAt(0); //removes the 3rd element (index starts from 0)
		
		foreach (var num in numbers)
			Console.WriteLine(num);
	}
}
 

Output


2
3
4
 

Check Elements in List Use the Contains() method to determine whether an element is in the List or not.

Example: Contains()


using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		var Name = new List(){ "shubham", "batra", "abir", "mohit" };

		Console.WriteLine(Name.Contains("shubham"));
		Console.WriteLine(Name.Contains("batra"));
		Console.WriteLine(Name.Contains("shubham batra"));
		Console.WriteLine(Name.Contains("mohit"));

	}
}
 

Output


True
True
False
True