OfTypeフィルタ演算子
プログラミングC# 第6版 8.3.1
OfTypeは指定した型のオブジェクトだけを抽出するフィルタです。
以下実行例。
using System; using System.Linq; class Foo { public int fooId; } class Bar { public int barId; } class Program { static void Main() { object[] objs = new object[] { new Foo() { fooId = 1 }, new Foo() { fooId = 2 }, new Bar() { barId = 10 }, new Bar() { barId = 20 }, }; // Bar型のオブジェクトだけを抽出する var ret = from obj in objs.OfType<Bar>() select obj; foreach(var item in ret) { Console.WriteLine(item.barId); } } }
$ main 10 20
Bar型だけがちゃんと表示されていますね。