Simon Heinen Simon Heinen - 11 months ago 72
C# Question

LINQ for System.Collections.IEnumerable


works with
but cant be used if the implemented interface is

My question is, why is that so?

Maybe a little bit of context, I want to use
on the
class of Unity, which implements
instead of
even though it only has
as children..
So I now created an extension method for
, feel free to use it:

/// <summary> Where-Filter implementation for transform to filter out specific children</summary>
public static IEnumerable<GameObject> WhereChild(this Transform s, Func<GameObject, bool> callback) {
List<GameObject> r = new List<GameObject>();
foreach (Transform cur in s) { if (callback(cur.gameObject)) { r.Add(cur.gameObject); } }
return r;

(Modify it if you want to work on the transforms and not the children Gameobjects instead, I like it more this way;)

Answer Source

Because most of those methods are generic and make little sense when you only get objects. A few methods are in fact declared as extension methods on IEnumerable instead of IEnumerable<T>, e.g. Cast<T>() and OfType<T>, both of which return a typed enumerable.

So in your case you can use Cast<object>() to reap the benefits of LINQ in the most useless manner, because the predicate for Where cannot really reasonably do much with an object without casting it anyway.