()selecta; works the same way for integer types. varmyInt=fromainlist.OfType Home >Backend Development >C#.Net Tutorial >C# OfType() method Filter the collection based on each element type. Suppose you have the following list containing integer and string elements - Filter the collection and get only the elements of string type. Works the same way for integer types. The following is the complete code - Real-time demonstration The above is the detailed content of C# OfType() method. For more information, please follow other related articles on the PHP Chinese website!C# OfType() method
list.Add("Katie");
list.Add(100);
list.Add(200);
var myStr = from a in list.OfType<string>() select a;
var myInt = from a in list.OfType<int>() select a;
Example
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);
}
}
}
Output
Strings...
Katie
Brad
Integer...
100
200
300
400
600
700