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 anIEnumerablewithout 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 implementsIEnumerablebut notIEnumerable<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.