TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Convert List to Array

These C# programs convert Lists and arrays. They use ToArray and ToList.

Convert list, array. A List can be converted to an array.

The opposite conversion is also needed. This is required in many programs—it is important to have it handy. We make sure the method works well. We look at it in the Visual Studio debugger.

List, array. There are two parts to this example. In part A, the example creates a new List and populates it with some strings. The List is a constructed type and can only hold strings. Next, in part B it uses ToArray on the List.

ToArray

C# program that uses ToArray

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
	// A.
	// New list here.
	List<string> l = new List<string>();
	l.Add("one");
	l.Add("two");
	l.Add("three");
	l.Add("four");
	l.Add("five");

	// B.
	string[] s = l.ToArray();
    }
}

To make sure it works, I looked at it in Visual Studio's debugger. To do this, compile the app in Debug mode, and set breakpoints on ToArray. Run it and you see the values. The array is a string array.

String Array

Array, List. We can convert an array of any number of elements to a List that has the same type of elements. There are three parts to this example. First, in part 1 it initializes a new string array containing five strings.

Next, in part 2A it converts the array to a List with the List constructor. And in part 2B, the example converts the array to a List with the ToList() parameterless instance method.

C# program that uses List constructor and ToList

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
	// 1.
	// String array
	string[] s = new string[]
	{
	    "one",
	    "two",
	    "three",
	    "four",
	    "five"
	};
	// 2A.
	// Convert with new List constructor.
	List<string> l = new List<string>(s);

	// 2B.
	List<string> l2 = s.ToList();
    }
}

In part 2A above, I use the new List<string>(string[]) constructor. This copies all the elements in the argument to the List. Each item must be separately copied. In part 2B, the ToList method is used.

Note: It is an extension method, which means it is an addition to normal C# method calls.

ToList

Internals. We look at how these methods are implemented in the base class libraries. You can use the IL Disassembler tool provided by Microsoft to look inside methods. It simply calls the List constructor.

So: That means 2A and 2B are the same except for a check against the null literal.

IL Disassembler Tutorial

 

Implicit conversion error. You may get the "Cannot implicitly convert type" error. This error raised by the compiler tells you that the type needs a regular cast or is not compatible.

Note: If your code statement tries to assign a List to an array, you will get this error.

Convert Lists and arrays—I feel that B and 2B are the clearest methods to read. It is easy for me to understand that ToList converts a collection to List, and ToArray does the same for an array.

Performance: I have not performed extensive micro-benchmarks on these conversion methods.

However: The constructor 2A would be the fastest for that example. You could code a loop that copies elements and it would be similar.

Summary. We converted Lists and arrays. Convert your arrays to Lists and vice versa with this code. You can't simply assign one to the other. You can find more information on converting collections or queries to arrays based on the ToArray method.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf