Mega Code Archive

 
Categories / C# Book / 04 LINQ
 

0408 OfType

OfType accepts a nongeneric IEnumerable collection and emit a generic IEnumerable<T> sequence that you can subsequently query: using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { ArrayList classicList = new ArrayList(); // in System.Collections classicList.AddRange(new int[] { 3, 4, 5 }); IEnumerable<int> sequence1 = classicList.OfType<int>(); foreach (int i in sequence1) { Console.WriteLine(i); } } } The output: 3 4 5 When encountering an incompatible type OfType ignores the incompatible element. using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Program { static void Main() { ArrayList classicList = new ArrayList(); // in System.Collections classicList.AddRange(new int[] { 3, 4, 5 }); IEnumerable<int> sequence1 = classicList.Cast<int>(); foreach (int i in sequence1) { Console.WriteLine(i); } DateTime offender = DateTime.Now; classicList.Add(offender); sequence1 = classicList.OfType<int>(); // OK - ignores offending DateTime foreach (int i in sequence1) { Console.WriteLine(i); } } } The output: 3 4 5 3 4 5