24
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【C#】Where(it => it is Xxx).Select(it => it as Xxx)って書かず、OfType使おう!【LINQ】

Posted at
UnityEngine.Object[] selectingObjects = Selection.objects;
Texture2D[] textures = selectingObjects
    .Where(it => it is Texture2D)
    .Select(it => it as Texture2D)
    .ToArray();

 このコードでは、WhereでTexture2Dなインスタンスだけになるよう選択して、Selectの中で要素をキャストして射影していますね。

 実はWhereSelect二つのメソッドを書かずとも、C#ではOfTypeメソッド一つを使って次のように簡潔に書くことが可能です。

UnityEngine.Object[] selectingObjects = Selection.objects;
Texture2D[] textures = selectingObjects
    .OfType<Texture2D>() // WhereとSelect二つもいらない、OfTypeでOK
    .ToArray();

 このように、OfTypeメソッド使えば、もとのシーケンス(IEnumerable<UnityEngine.Object>)に型引数を指定して、Texture2Dのインスタンスのみのシーケンス、IEnumerablet<Texture2D>にすることができます。

 Where(it => it is Xxx).Select(it => it as Xxx)って書かずに、OfType使いましょう!!!

24
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?