While you can't do this directly, you could do it via Cast
:
if (enumerable.Cast<object>().Any())
That should always work, as any IEnumerable
can be wrapped as an IEnumerable<object>
. It will end up boxing the first element if it's actually an IEnumerable<int>
or similar, but it should work fine. Unlike most LINQ methods, Cast
and OfType
target IEnumerable
rather than IEnumerable<T>
.
You could write your own subset of extension methods like the LINQ ones but operating on the non-generic IEnumerable
type if you wanted to, of course. Implementing LINQ to Objects isn't terribly hard - you could use my Edulinq project as a starting point, for example.
There are cases where you could implement Any(IEnumerable)
slightly more efficiently than using Cast
- for example, taking a shortcut if the target implements the non-generic ICollection
interface. At that point, you wouldn't need to create an iterator or take the first element. In most cases that won't make much performance difference, but it's the kind of thing you could do if you were optimizing.