Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# - List<T>

The List<T> 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.Collections.Generic namespace.

List<T> Characteristics

  • List<T> equivalent of the ArrayList, which implements IList<T>.
  • It comes under System.Collections.Generic namespace.
  • List<T> can contain elements of the specified type. It provides compile-time type checking and doesn't perform boxing-unboxing because it is generic.
  • Elements can be added using the Add(), AddRange() methods or collection-initializer syntax.
  • Elements can be accessed by passing an index e.g. myList[0]. Indexes start from zero.
  • List<T> performs faster and less error-prone than the ArrayList.

Creating a List

The List<T> 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 list and add elements.

Example: Adding elements in List
List<int> primeNumbers = new List<int>();
primeNumbers.Add(2); // adding elements using add() method
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);

var cities = new List<string>();
cities.Add("New York");
cities.Add("London");
cities.Add("Mumbai");
cities.Add("Chicago");
cities.Add(null);// nulls are allowed for reference type list

//adding elements using collection-initializer syntax
var bigCities = new List<string>()
                    {
                        "New York",
                        "London",
                        "Mumbai",
                        "Chicago"                    
                    };
Try it

In the above example, List<int> primeNumbers = new List<int>(); creates a list of int type. In the same way, cities and bigCities 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<Student>.

Example: Add Custom Class Objects in List
var students = new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"}
            };

Adding an Array in a List

Use the AddRange() method to add all the elements from an array or another collection to List.

AddRange() signature: void AddRange(IEnumerable<T> collection)

Example: Add Arrays in List
string[] cities = new string[3]{ "Mumbai", "London", "New York" };

var popularCities = new List<string>();

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

var favouriteCities = new List<string>();

// adding a List 
favouriteCities.AddRange(popularCities);
Try it

Accessing a List

A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero. Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.

Example: Accessing List
List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };
Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 2
Console.WriteLine(numbers[2]); // prints 5
Console.WriteLine(numbers[3]); // prints 7

// using foreach LINQ method
numbers.ForEach(num => Console.WriteLine(num + ", "));//prints 1, 2, 5, 7, 8, 10,

// using for loop
for(int i = 0; i < numbers.Count; i++)
    Console.WriteLine(numbers[i]);
Try it

Accessing a List using LINQ

The List<T> 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
var students = new List<Student>() { 
                new Student(){ Id = 1, Name="Bill"},
                new Student(){ Id = 2, Name="Steve"},
                new Student(){ Id = 3, Name="Ram"},
                new Student(){ Id = 4, Name="Abdul"}
            };

//get all students whose name is Bill
var result = from s in students
	     where s.Name == "Bill"
	     select s;
		
foreach(var student in result)
    Console.WriteLine(student.Id + ", " + student.Name);
Try it

Insert Elements in List

Use the Insert() method inserts an element into the List<T> collection at the specified index.

Insert() signature:void Insert(int index, T item);

Example: Insert elements into List
var numbers = new List<int>(){ 10, 20, 30, 40 };

numbers.Insert(1, 11);// inserts 11 at 1st index: after 10.

foreach (var num in numbers)
    Console.Write(num);
Try it

Remove Elements from List

Use the Remove() method to remove the first occurrence of the specified element in the List<T> 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
var numbers = new List<int>(){ 10, 20, 30, 40, 10 };

numbers.Remove(10); // removes the first 10 from a list

numbers.RemoveAt(2); //removes the 3rd element (index starts from 0)

//numbers.RemoveAt(10); //throws ArgumentOutOfRangeException

foreach (var el in intList)
    Console.Write(el); //prints 20 30
Try it

Check Elements in List

Use the Contains() method to determine whether an element is in the List<T> or not.

Example: Contains()
var numbers = new List<int>(){ 10, 20, 30, 40 };
numbers.Contains(10); // returns true
numbers.Contains(11); // returns false
numbers.Contains(20); // returns true
Try it

List<T> Class Hierarchy

The following diagram illustrates the List<T> hierarchy.

C# List Class Hierarchy

List<T> Class Properties and Methods

The following table lists the important properties and methods of List<T> class:

PropertyUsage
ItemsGets or sets the element at the specified index
CountReturns the total number of elements exists in the List<T>
MethodUsage
AddAdds an element at the end of a List<T>.
AddRangeAdds elements of the specified collection at the end of a List<T>.
BinarySearchSearch the element and returns an index of the element.
ClearRemoves all the elements from a List<T>.
ContainsChecks whether the specified element exists or not in a List<T>.
FindFinds the first element based on the specified predicate function.
ForeachIterates through a List<T>.
InsertInserts an element at the specified index in a List<T>.
InsertRangeInserts elements of another collection at the specified index.
RemoveRemoves the first occurrence of the specified element.
RemoveAtRemoves the element at the specified index.
RemoveRangeRemoves all the elements that match the supplied predicate function.
SortSorts all the elements.
TrimExcessSets the capacity to the actual number of elements.
TrueForAllDetermines whether every element in the List<T> matches the conditions defined by the specified predicate.
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.