Dot Net Perls

Convert List to Array - C#

by Sam Allen

Problem

Convert your List to an array, or the opposite. This is needed in many programs and it is important to have it handy. Make sure your method works well and look at it in the debugger.

Solution: converting Lists in C#

First we have to convert our List to an array. The example shows how to make a new List and then turn it into a string[] array.

Example: convert from List to array

There are two parts to this example. A. It creates a new List and populates it with some strings. The List is a generic and can only hold strings. B. It uses ToArray on the List.

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();
    }
}

Does it work? 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.

Example: convert from array to List

There are three parts to this example. 1. It initializes a new string[] array containing 5 strings. 2A. It converts to List with new List constructor. 2B. It converts to List with 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();
    }
}

Information: converting array to List comparison

In 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.

How ToList works. In 2B, the ToList method is used. It is an extension method, which means it is an addition to normal C# syntax. You need System.Linq for this.

Information: looking inside ToList()

I opened Red Gate's Reflector program and "reflected" inside ToList(). It calls the exact same List constructor. That means 2A and 2B are the same except for a null check.

public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    return new List<TSource>(source);
}

Information: "cannot implicitly convert type" error

This error raised by the compiler tells you that the type needs a regular cast or is not compatible. If you try to assign a List to an array, you will get this error.

Opinion: the best way to convert array to List

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

Question: what's the fastest way?

I don't know for sure. However, the constructor at 2A would be the fastest for that example. You could code your own loop that copies elements and it would probably be almost the same.

Summary: converting Lists and arrays

Convert your arrays to Lists and vice-versa with this code. I offered a view into the debugger and looked into Reflector to see the IL. You can't simply assign one to the other.

Dot Net Perls
About
Sitemap
Conversion
Convert Char Array to String
Convert List to Array
Convert Bytes to Megabytes
Convert Dictionary to String
Convert Degrees Celsius to Fahrenheit
New
StartsWith String Examples
GZIP Accept-Encoding Request
© 2008 Sam Allen. All rights reserved.