List in C#

From previous articles we learned about Dictionary<TKey,TValue>. To learn more click here.

A list<T> class can be used to create a collection of any type, like List<double>, List<String> and List<int>. We can even create a list of complex types, like List<Student>, List<Customer> and so on.

Let's look at an example.

Example 1

In this example we will create a list of simple type.

In my console application, I have a class Program in which there is a main method.

method

In this main method, we will create a list of integers.

To create a list, we can say.

  1. static void Main(string[] args) {  
  2.    List<  
  3. }  
create a list

T stands for the type of list collection we want to create.

We will be creating a list of integers. So, we will pass an int.
  1. static void Main(string[] args) {  
  2.    List<int> NumericList = new List<int>(int capacity);  
  3. }  
T stands

There are three overloaded versions of the List constructor. In the second overloaded version we can pass the capacity of integer items that we will add to this NumericList collection.
  1. List<int> NumericList = new List<int>(3);  
Now let's add some items to this list collection and to add items, we can use the Add method.

collection

Look at the type. This Add method parameter expects an “int” because we have created this list collection of type int. So, all the items that we pass can only be of type int or else we will get a compiler error.

Add method

We have added three items to the list object.

Now what will happen if I add another item to the NumericList?

We have assigned the capacity of 3 for this list collection. So, will we get a compiler error?

Let's see this practically.
  1. //adding a fourth item  
  2. NumericList.Add(4);  
Build the project.

Build the project

At the bottom-left you can see a message “build succeeded”. So, the answer is No. We will not get any error even if the total items that we add is greater than the size of the capacity because lists can grow in size automatically.

**Now let's see how to retrieve an item from this list collection**

The items stored in a list can be accessed by Index. Let's see this practically.

items

The return type is an int. That means we can store a value in a variable of type integer.

store value

Here in the preceding we have assigned the value of the item whose index position is 0. That means the first item in the NumericList.

Let's display the value on the console screen.

display the value

Run the application.

Run the application

Now let's say we want to retrieve all the items from this NumericList collection and whenever we want to retrieve a series or collection of items, we can use a foreach loop to loop through each item present in the Source collection and here the collection is NumericList.

NumericList

Run the application.

Run application

We can achieve the same output using a for loop.

for loop

Run the application.

output

Now let's say we want to add another item “5” and we want this item to be displayed after 1. To do this we can use an Insert method.

Insert method

The first parameter is the Index position and the second parameter is the actual item.

Index position

Run the application.

Run

In the output, 5 is inserted just after 1.

There is another method “InsertRange” and using that we can pass another range of List<int> collection.

inserted

The first parameter is the Index position and the second parameter expects a collection of type IEnumerable<int> and here we can pass a new list collection because all the generic class inherits directly or indirectly from the IEnumerable interface.

InsertRange

The items will be displayed just after the value 5 because the Index value of 5 is 1 and the index value of this newly added range is 2.

Run the application.

displayed

Example 2

In this example we will see how to create a list of complex type.

I have created a new console application in which there are two classes in a single .cs file.

The “Student” class has four auto-implemented properties.
  1. class Student {  
  2.    public int StudentId { getset; }  
  3.    public string Name { getset; }  
  4.    public string Gender { getset; }  
  5.    public double TotalMarks { getset; }  
  6. }  
The “Program” class has a main method were I have created five objects of the Student class and assigned values for all the properties.
  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         Student sOne = new Student() {  
  4.             StudentId = 101, Name = "Lara Croft", Gender = "Female", TotalMarks = 450.55  
  5.         };  
  6.   
  7.         Student sTwo = new Student() {  
  8.             StudentId = 102, Name = "Sam Fisher", Gender = "Male", TotalMarks = 341  
  9.         };  
  10.   
  11.         Student sThree = new Student() {  
  12.             StudentId = 103, Name = "Aiden Pearce", Gender = "Male", TotalMarks = 750.32  
  13.         };  
  14.   
  15.         Student sFour = new Student() {  
  16.             StudentId = 104, Name = "Michael", Gender = "Male", TotalMarks = 612  
  17.         };  
  18.   
  19.         Student sFive = new Student() {  
  20.             StudentId = 105, Name = "Black Widow", Gender = "Female", TotalMarks = 464  
  21.         };  
  22.   
  23.     }  
  24. }  
The next step is to create a new List<Student> object and for that we can say:
  1. List<Student> StudentList = new List<Student>();  
We have specified the type for this list collection as Student.

The next step is to add the five student objects that we have created in this StudentList collection and for that we will use the Add method. Now if you look at the following Add method, this Add method expects an object of type Student. In Example 1 the same Add method was expecting a value of type int.

So, based on the type of list we create, we pass the value or object of that type.

type of list

object of that type

We have added all the Student objects to this list collection.

The next step is to retrieve a record from the list object and for that we can say:
  1. StudentList[PassTheIndexValue]  
Look at what this StudentList[Index] will return.

return

It is returning us a Student object back that means we can store the records in a new Student object.

So, let's see how to do it.
  1. Student s = StudentList[0];  
That's it. Now all the properties of the first item, sOne, is now available in the new Student object “s” and all we need to do is print the details on the console screen.
  1. Console.WriteLine("Student Id is {0}, Student Name is {1}, Student Gender is {2}, Student Marks is {3}",s.StudentId,s.Name,s.Gender,s.TotalMarks);  
This is how the entire cs file looks:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. namespace ComplexList {  
  5.     class Student {  
  6.         public int StudentId { getset; }  
  7.         public string Name { getset; }  
  8.         public string Gender { getset; }  
  9.         public double TotalMarks { getset; }  
  10.     }  
  11.   
  12.     class Program {  
  13.         static void Main(string[] args) {  
  14.             Student sOne = new Student() {  
  15.                 StudentId = 101,  
  16.                 Name = "Lara Croft",  
  17.                 Gender = "Female",  
  18.                 TotalMarks = 450.55  
  19.             };  
  20.   
  21.             Student sTwo = new Student() {  
  22.                 StudentId = 102,  
  23.                 Name = "Sam Fisher",  
  24.                 Gender = "Male",  
  25.                 TotalMarks = 341  
  26.             };  
  27.   
  28.             Student sThree = new Student() {  
  29.                 StudentId = 103,  
  30.                 Name = "Aiden Pearce",  
  31.                 Gender = "Male",  
  32.                 TotalMarks = 750.32  
  33.             };  
  34.   
  35.             Student sFour = new Student() {  
  36.                 StudentId = 104,  
  37.                 Name = "Michael",  
  38.                 Gender = "Male",  
  39.                 TotalMarks = 612  
  40.             };  
  41.   
  42.             Student sFive = new Student() {  
  43.                 StudentId = 105,  
  44.                 Name = "Black Widow",  
  45.                 Gender = "Female",  
  46.                 TotalMarks = 464  
  47.             };  
  48.   
  49.             List<Student> StudentList = new List<Student>();  
  50.             StudentList.Add(sOne);  
  51.             StudentList.Add(sTwo);  
  52.             StudentList.Add(sThree);  
  53.             StudentList.Add(sFour);  
  54.             StudentList.Add(sFive);  
  55.   
  56.             Student s = StudentList[0];  
  57.   
  58.   
  59.             Console.WriteLine("Student Id  is {0}, Student Name is {1}, Student Gender is {2}, Student Marks is {3}",s.StudentId,s.Name,s.Gender,s.TotalMarks);  
  60.         }  
  61.     }  
  62. }  
Run the application.

Run program

To retrieve all the items from the StudentList list collection we can use a foreach loop. Let's see how to do that.
  1. foreach(Student s in StudentList) {  
  2.    Console.WriteLine("Student Id is {0}, Student Name is {1}, Student Gender is {2}, Student Marks is {3}", s.StudentId, s.Name, s.Gender, s.TotalMarks);  
  3. }  
Run the application.

StudentList list collection

The following are some important and useful methods of the List class.

Contains() Method

If you are not sure that a specific item exits in the list then use the Contains() method. This is a Boolean method that returns true or false.
  1. if(StudentList.Contains(sTwo)) {  
  2.    Console.WriteLine("The StudentList contains this item");  
  3. }  
  4. else {  
  5.    Console.WriteLine("The StudentList does not contain item");  
  6. }  
Run the application.

Contains Method

Exists() Method

If you want to look for an item that exists in the list collection based on condition then use the Exists method. This is a Boolean method.

This method expects a predicate.

Exists Method
  1. if(StudentList.Exists(s => s.TotalMarks < 400)) {  
  2.    Console.WriteLine("The item exists");  
  3. }  
  4. else {  
  5.    Console.WriteLine("The item not found");  
  6. }  
The predicate s => s.TotalMarks < 400. This s => is nothing but a parameter of type Student.

s.TotalMarks < 400 is the expression where we are checking if the TotalMarks is less than 400.

TotalMarks

Find() Method

Let's say we have a condition and based on that condition we get three matching results and from that we want only the first matching result. For that we can use the Find() method.

StudentList.Find(

Find Method

The return type of this Find method is the type of the List, which is Student.

So, now let's pass a lambda expression in this Find method parameter.

Let's say we want the student name whose TotalMarks is greater than 500 and this find method will provide only the first matching item.
  1. Student student = StudentList.Find(s => s.TotalMarks > 500);  
  2. S => is the parameter of type Student  
  3. s.TotalMarks > 500 is the expression.  
Now all we need to do is to print the name on the console screen.
  1. Console.WriteLine(student.Name);  
print the name

Note

If you want to find the last matching item, use the FindLast() method instead of the Find method.

FindAll() Method

If you want to find all the matching rows that match the condition specified by the lambda expression then use the FindAll method.

The result type of this method is List<T> and here the type is Student.

FindAll Method
  1. List<Student> NewStudentList = StudentList.FindAll(s => s.TotalMarks > 500);  
Since it is a list, we need to loop through each item and for that we can use a foreach loop.
  1. foreach(Student s in NewStudentList) {  
  2.    Console.WriteLine(s.Name);  
  3. }  
Run the application.

use foreach loop

FindIndex() Method

If you want to return the index of the first matching row based on the specified lambda condition, use the FindIndex() method.
  1. int index = StudentList.FindIndex(x => x.TotalMarks > 750);  
  2. Console.WriteLine(index);  
Run the application.

FindIndex

Which is this student record.
  1. Student sThree = new Student() {  
  2. StudentId = 103,  
  3. Name = "Aiden Pearce",  
  4. Gender = "Male",  
  5. TotalMarks = 750.32  
  6. };  
There are two more overloaded versions of this FindIndex() method.

The following is the second overloaded version.

second overloaded

If you want to start the search from a specific index position like 2 or 3 (this base value is included) then use this overloaded version.

Let's say we want to start this from Index position 3.
  1. int index = StudentList.FindIndex(3,x => x.TotalMarks > 750);  
  2. Console.WriteLine(index);  
Run the application.

from Index position

We got the output as -1 because there are no records whose TotalMarks is greater than 750.

The final overloaded version of this method is the count parameter.

final overloaded version

Let's say there are 10 items in a list collection and you want to find the Index of the item whose TotalMarks is greater than 500. But you want to start the search from index position 2, meaning it will remove the first two items from the search queue. So, there are 8 items left but you want to search only the 3 items from index position 2. So, we need to pass 3 in the count parameter and it will only search for the matching records in the next three items, including the indexed item.

Note

If you want to find the last index then use the FindLastIndex() method.

So, in this article we have seen how to create a simple type list collection and a complex type list collection. We have also seen some of the useful methods of the List class.

I hope you like it. Thank you.

Up Next
    Ebook Download
    View all
    Learn
    View all