Conversion Methods

LINQ deals primarily in sequences; in other words, collections of type IEnumerable<T>. The conversion methods convert to and from, other types of collections:

Method

Description

OfType

Converts IEnumerable to IEnumerable<T>, discarding wrongly typed elements

Cast

Converts IEnumerable to IEnumerable<T>, throwing an exception if there are any wrongly typed elements

ToArray

Converts IEnumerable<T> to T[]

ToList

Converts IEnumerable<T> to List<T>

ToDictionary

Converts IEnumerable<T> to Dictionary<TKey,TValue>

ToLookup

Converts IEnumerable<T> to ILookup<TKey,TElement>

AsEnumerable

Downcasts to IEnumerable<T>

AsQueryable

Casts or converts to IQueryable<T>

OfType and Cast

OfType and Cast accept a nongeneric IEnumerable collection and emit a generic IEnumerable<T> sequence that you can subsequently query:

	// ArrayList is defined in System.Collections
	ArrayList classicList = new ArrayList();
	classicList.AddRange ( new int[] { 3, 4,5 } );
	IEnumerable<int> sequence1 =classicList.Cast<int>();

Cast and OfType differ in their behavior when encountering an input element that’s of an incompatible type. Cast throws an exception; OfType ignores the incompatible element. Continuing the preceding example:

	DateTime offender = DateTime.Now;
	classicList.Add (offender);

	IEnumerable<int> sequence2 = classicList
	  .OfType<int>();     // OK - Ignoresoffending DateTime

	IEnumerable<int> sequence3 = classicList
	  .Cast<int>();       // Throws exception

The rules for element compatibility exactly follow those ...

Get LINQ Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.