O'Reilly logo

LINQ Pocket Reference by Joseph Albahari, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required