CSharp - LINQ ToArray


The ToArray operator creates an array of type T from an input sequence of type T.


public static T[] ToArray<T>(
  this IEnumerable<T> source);

This operator takes an input sequence named source, of type T elements, and returns an array of type T elements.


ArgumentNullException is thrown if the source argument is null.

The following code will create a sequence of that type by calling the OfType operator on an array.

Once we have that sequence, we can call the ToArray operator to create an array.


using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w ww .ja v  a2s. c o m*/
    static void Main(string[] args)
         string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
         string[] names = codeNames.OfType<string>().ToArray();
         foreach (string name in names)


First we convert the codeNames array to a sequence of type IEnumerable<string> using the OfType operator.

Then we convert that sequence to an array using the ToArray operator.

Since the ToArray is a non deferred operator, the query is performed immediately.