LINQ ToList and ToArray Methods in C#

LINQ ToList and ToArray Methods in C# with Examples

In this article, I am going to discuss the LINQ ToList and ToArray Methods in C# with Examples. Please read our previous article where we discussed LINQ Zip Method in C# with Examples. The LINQ ToList and ToArray Methods in C# belong to the conversion operator category.

LINQ ToList Method in C#:

The LINQ ToList Method in C# is used to create a System.Collections.Generic.List<T> collection from a System.Collections.Generic.IEnumerable<T>. This method causes the query to be executed immediately. The signature of the ToList method is shown below.

ToList and ToArray Methods in Linq with Examples

Parameters:
  • source: The data type of source is System.Collections.Generic.IEnumerable<T>.
Type parameters:
  • TSource: The type of elements contained in the source sequence.
Returns:
  • It returns System.Collections.Generic.List<T> which contains elements from the source sequence.
Exceptions:
  • This method throws System.ArgumentNullException when the source sequence is null.
Example to Convert int array to List<int> using the LINQ ToList Method in C#

In the following example, first, we create an integer array and then we convert that integer array into a list (i.e. List<int>) by using the LINQ ToList Method in C#. 

using System.Collections.Generic;
using System.Linq;
using System;
namespace LINQToListMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Creating Integer Array
            int[] numbersArray = { 10, 22, 30, 40, 50, 60 };

            //Converting Integer Array to List using ToList method
            List<int> numbersList = numbersArray.ToList();

            //Accessing the List Elements
            foreach (var num in numbersList)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

Output: 10 22 30 40 50 60

Working with Complex Type:

Let us see how we can work with the ToArray method of a collection of Complex Types. For this, we are going to use the following Employee class. So, create a class file with the name Employee.cs and then copy and paste the following code into it. It’s a very simple class having only three properties.

namespace LINQToArrayMethodDemo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Department { get; set; }
    }
}

Next, modify the Main method of the Program class as follows. As you can see, first, we are creating an array of type Employee and storing 5 employee information. Then we are converting that array of Employees to a list of Employees by calling the ToList Method.

using System.Collections.Generic;
using System.Linq;
using System;
namespace LINQToArrayMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Create an Array of Employees
            Employee[] EmployeesArray = new Employee[]
            {
                new Employee() {ID = 1, Name = "Pranaya", Department = "IT" },
                new Employee() {ID = 2, Name = "Priyanka", Department = "HR" },
                new Employee() {ID = 3, Name = "Preety", Department = "HR" },
                new Employee() {ID = 4, Name = "Sambit", Department = "IT" },
                new Employee() {ID = 5, Name = "Sudhanshu", Department = "IT"}
            };

            //Converting Array to List
            List<Employee> EmployeesList = EmployeesArray.ToList();

            //Accessing the Elements of the List
            foreach (var emp in EmployeesArray)
            {
                Console.WriteLine($"ID: {emp.ID}, Name: {emp.Name}, Department: {emp.Department}");
            }

            Console.ReadKey();
        }
    }
}
Output:

Working with Complex Type

What happens when the Source Array is Null?

When the Source Array is Null and if we try to convert that null array into a list using the ToList method, then we will get one runtime exception saying the value cannot be null. For a better understanding, please have a look at the following example. In the below example, we are creating one null array and then converting that integer null array to a list.

using System.Collections.Generic;
using System.Linq;
using System;
namespace LINQToListMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Creating Integer Array and Initializing it with NULL
            int[] numbersArray = null;

            //Converting Integer Array to List using ToList method
            List<int> numbersList = numbersArray.ToList();

            //Accessing the List Elements
            foreach (var num in numbersList)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following exception at runtime.

LINQ ToList and ToArray Methods in C# with Examples

LINQ ToArray Method in C#:

The LINQ ToArray Method in C# is used to copy the elements of the System.Collections.Generic.List<T> to a new array. This method causes the query to be executed immediately. The signature of this method is shown below.

Linq ToArray Method

Here T is the type of the array and this method converts a list into an array and returns that array containing copies of the elements of the System.Collections.Generic.List<T>.

Example to Convert List<int> to Integer Array in C# using LINQ ToArray Method. 

In the following example, first, we create a list of integers and then convert that list of integers into an integer array (i.e. int[]) by using the LINQ ToArray Method in C#. The following code is self-explained, so please go through the comment lines for a better understanding.

using System.Collections.Generic;
using System;
namespace LINQToArrayMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Create a List
            List<int> numbersList = new List<int>()
            {
                10, 22, 30, 40, 50, 60
            };

            //Converting List to Array
            int[] numbersArray = numbersList.ToArray();

            //Accessing the Elements of the Array
            foreach (var num in numbersArray)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

Output: 10 22 30 40 50 60

Working with Complex Type:

We are going to work with the same Employee class. So, modify the Main method of the Program class as follows. As you can see, first, we are creating a list collection of type Employees and storing 5 employee information. Then we are converting that list of Employees to an array of Employees by calling the ToArray Method.

using System.Collections.Generic;
using System;
namespace LINQToArrayMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Create a List of Employees
            List<Employee> EmployeesList = new List<Employee>()
            {
                new Employee() {ID = 1, Name = "Pranaya", Department = "IT" },
                new Employee() {ID = 2, Name = "Priyanka", Department = "HR" },
                new Employee() {ID = 3, Name = "Preety", Department = "HR" },
                new Employee() {ID = 4, Name = "Sambit", Department = "IT" },
                new Employee() {ID = 5, Name = "Sudhanshu", Department = "IT"}
            };

            //Converting List to Array
            Employee[] EmployeesArray = EmployeesList.ToArray();

            //Accessing the Elements of the Array
            foreach (var emp in EmployeesArray)
            {
                Console.WriteLine($"ID: {emp.ID}, Name: {emp.Name}, Department: {emp.Department}");
            }

            Console.ReadKey();
        }
    }
}
Output:

Working with Complex Type

What Happens when we call the ToArray Method on a List which is Null?

If we call the ToArray Method on a List that is Null, then we will get Null Reference Exception. For a better understanding, please have a look at the following example. In the below example, we are creating one list and initializing that list with NULL, and then calling the ToArrya method on that list instance.

using System.Collections.Generic;
using System;
namespace LINQToArrayMethodDemo
{
    class Program
    {
        public static void Main()
        {
            //Create a List
            List<int> numbersList = null;

            //Converting List to Array
            int[] numbersArray = numbersList.ToArray();

            //Accessing the Elements of the Array
            foreach (var num in numbersArray)
            {
                Console.Write($"{num} ");
            }

            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following Exception.

What Happens when we call the ToArray Method on a List which is Null

In the next article, I am going to discuss the LINQ ToDictionary Method in C# with Examples. Here, in this article, I try to explain the need and use of LINQ ToList and ToArray Methods in C# with Examples. I hope you enjoy this LINQ ToList and ToArray Methods in C# article.

Leave a Reply

Your email address will not be published. Required fields are marked *