Simon Heinen Simon Heinen - 3 months ago 17
C# Question

LINQ for System.Collections.IEnumerable

LINQ

Where()
works with
System.Collections.Generic.IEnumerable<T>
but cant be used if the implemented interface is
System.Collections.IEnumerable


My question is, why is that so?

Update:
Maybe a little bit of context, I want to use
.Where()
on the
Transform
class of Unity, which implements
System.Collections.IEnumerable
instead of
System.Collections.Generic.IEnumerable<Transform>
even though it only has
Transforms
as children..
So I now created an extension method for
Transform
, 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

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.