C# Enumerable ToArray

Description

Creates an array from a IEnumerable .

Syntax


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

Parameters

  • TSource - The type of the elements of source.
  • source - An IEnumerable to create an array from.

Example

The following code example demonstrates how to use ToArray to force immediate query evaluation and return an array of results.


/*from  www . ja  va 2  s  . com*/
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(){
    List<Package> packages =
        new List<Package> 
            { new Package { Company = "A", Weight = 25.2 },
              new Package { Company = "B", Weight = 18.7 },
              new Package { Company = "C", Weight = 6.0 },
              new Package { Company = "D", Weight = 33.8 } };
  
    string[] companies = packages.Select(pkg => pkg.Company).ToArray();
  
    foreach (string company in companies)
    {
        Console.WriteLine(company);
    }
  }
}
    
class Package{
   public string Company { get; set; }
   public double Weight { get; set; }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable