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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access