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 |
---|---|
| Converts |
| Converts |
| Converts |
| Converts |
| Converts |
| Converts |
| Downcasts to |
| Casts or converts to |
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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.