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.
In this main method, we will create a list of integers.
To create a list, we can say.
- static void Main(string[] args) {
- 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.
- static void Main(string[] args) {
- List<int> NumericList = new List<int>(int capacity);
- }
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.
- 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.
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.
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.
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.
The return type is an int. That means we can store a value in a variable of type integer.
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.
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.
Run the application.
We can achieve the same output using a for loop.
Run the application.
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.
The first parameter is the Index position and the second parameter is the actual item.
Run the application.
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.
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.
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.
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.
- class Student {
- public int StudentId { get; set; }
- public string Name { get; set; }
- public string Gender { get; set; }
- public double TotalMarks { get; set; }
- }
The “
Program” class has a main method were I have created five objects of the Student class and assigned values for all the properties.
- class Program {
- static void Main(string[] args) {
- Student sOne = new Student() {
- StudentId = 101, Name = "Lara Croft", Gender = "Female", TotalMarks = 450.55
- };
-
- Student sTwo = new Student() {
- StudentId = 102, Name = "Sam Fisher", Gender = "Male", TotalMarks = 341
- };
-
- Student sThree = new Student() {
- StudentId = 103, Name = "Aiden Pearce", Gender = "Male", TotalMarks = 750.32
- };
-
- Student sFour = new Student() {
- StudentId = 104, Name = "Michael", Gender = "Male", TotalMarks = 612
- };
-
- Student sFive = new Student() {
- StudentId = 105, Name = "Black Widow", Gender = "Female", TotalMarks = 464
- };
-
- }
- }
The next step is to create a new List<Student> object and for that we can say:
- 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.
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:
- StudentList[PassTheIndexValue]
Look at what this StudentList[Index] will 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.
- 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.
- 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:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace ComplexList {
- class Student {
- public int StudentId { get; set; }
- public string Name { get; set; }
- public string Gender { get; set; }
- public double TotalMarks { get; set; }
- }
-
- class Program {
- static void Main(string[] args) {
- Student sOne = new Student() {
- StudentId = 101,
- Name = "Lara Croft",
- Gender = "Female",
- TotalMarks = 450.55
- };
-
- Student sTwo = new Student() {
- StudentId = 102,
- Name = "Sam Fisher",
- Gender = "Male",
- TotalMarks = 341
- };
-
- Student sThree = new Student() {
- StudentId = 103,
- Name = "Aiden Pearce",
- Gender = "Male",
- TotalMarks = 750.32
- };
-
- Student sFour = new Student() {
- StudentId = 104,
- Name = "Michael",
- Gender = "Male",
- TotalMarks = 612
- };
-
- Student sFive = new Student() {
- StudentId = 105,
- Name = "Black Widow",
- Gender = "Female",
- TotalMarks = 464
- };
-
- List<Student> StudentList = new List<Student>();
- StudentList.Add(sOne);
- StudentList.Add(sTwo);
- StudentList.Add(sThree);
- StudentList.Add(sFour);
- StudentList.Add(sFive);
-
- Student s = StudentList[0];
-
-
- 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);
- }
- }
- }
Run the application.
To retrieve all the items from the StudentList list collection we can use a foreach loop. Let's see how to do that.
- foreach(Student s in StudentList) {
- 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);
- }
Run the application.
The following are some important and useful methods of the List class.
Contains() MethodIf 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.
- if(StudentList.Contains(sTwo)) {
- Console.WriteLine("The StudentList contains this item");
- }
- else {
- Console.WriteLine("The StudentList does not contain item");
- }
Run the application.
Exists() MethodIf 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.
- if(StudentList.Exists(s => s.TotalMarks < 400)) {
- Console.WriteLine("The item exists");
- }
- else {
- Console.WriteLine("The item not found");
- }
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.
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(
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.
- Student student = StudentList.Find(s => s.TotalMarks > 500);
- S => is the parameter of type Student
- s.TotalMarks > 500 is the expression.
Now all we need to do is to print the name on the console screen.
- Console.WriteLine(student.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.
- 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.
- foreach(Student s in NewStudentList) {
- Console.WriteLine(s.Name);
- }
Run the application.
FindIndex() Method
If you want to return the index of the first matching row based on the specified lambda condition, use the FindIndex() method.
- int index = StudentList.FindIndex(x => x.TotalMarks > 750);
- Console.WriteLine(index);
Run the application.
Which is this student record.
- Student sThree = new Student() {
- StudentId = 103,
- Name = "Aiden Pearce",
- Gender = "Male",
- TotalMarks = 750.32
- };
There are two more overloaded versions of this FindIndex() method.
The following is the second overloaded version.
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.
- int index = StudentList.FindIndex(3,x => x.TotalMarks > 750);
- Console.WriteLine(index);
Run the application.
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.
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.