How does one convert from an IEnumerable to IEnumerable<T>?

Someone asked on Stack Overflow:

Is there a way to get an IEnumerable<T> from an IEnumerable without reflection, assuming I know the type at design time?

I have this

foreach(DirectoryEntry child in de.Children)
{
   // long running code on each child object
}

I am trying to enable parallelization, like so

Parallel.ForEach(de.Children, 
    (DirectoryEntry child) => { // long running code on each child });

but this doesn’t work, as de.Children is of type DirectoryEntries. It implements IEnumerable but not IEnumerable<DirectoryEntry>.

I posted the following answer, which was chosen as the accepted answer and received 6 upvotes:

The way to achieve this is to use the .Cast<T>() extension method.

Parallel.ForEach(de.Children.Cast<DirectoryEntry>(), 
    (DirectoryEntry child) => { // long running code on each child });

Another way to achieve this is to use the .OfType<T>() extension method.

Parallel.ForEach(de.Children.OfType<DirectoryEntry>(), 
    (DirectoryEntry child) => { // long running code on each child });

There is a subtle different between .Cast<T>() and .OfType<T>()

The OfType(IEnumerable) method returns only those elements in source that can be cast to type TResult. To instead receive an exception if an element cannot be cast to type TResult, use Cast(IEnumerable).

— MSDN

This link on the MSDN forums got me going the right direction.

Notable comments

Tim Schmelter (3 upvotes): @KooKiz: But pointless if you know that every element is a DirectoryEntry anyway. OfType filters and casts, so if you need to filter use OfType otherwise Cast.


Originally posted on Stack Overflow — 6 upvotes (accepted answer). Licensed under CC BY-SA.

signed letter b

Dad. Geek. Gamer. Software developer. Cloud user. Old Car enthusiast.  Blogger.


Top Posts


profile for Nate on Stack Exchange, a network of free, community-driven Q&A sites
a proud member of the blue team of 512KB club
Thoughts, opinions, and ideas shared here are my own. © 2026 Nate Bross.