Filter the collection based on each element type.
Suppose you have the following list containing integer and string elements -
list.Add("Katie"); list.Add(100); list.Add(200);
Filter the collection and get only the elements of string type.
var myStr = from a in list.OfType<string>() select a;
Works the same way for integer types.
var myInt = from a in list.OfType<int>() select a;
The following is the complete code -
Real-time demonstration
using System; using System.Linq; using System.Collections; public class Demo { public static void Main() { IList list = new ArrayList(); list.Add("Katie"); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add("Brad"); list.Add(600); list.Add(700); var myStr = from a in list.OfType<string>() select a; var myInt = from a in list.OfType<int>() select a; Console.WriteLine("Strings..."); foreach (var strVal in myStr) { Console.WriteLine(strVal); } Console.WriteLine("Integer..."); foreach (var intVal in myInt) { Console.WriteLine(intVal); } } }
Strings... Katie Brad Integer... 100 200 300 400 600 700
The above is the detailed content of C# OfType() method. For more information, please follow other related articles on the PHP Chinese website!