I really love using the IEnumerable extension methods.
But sometimes I end up with some collection that only implements IEnumerable and so they aren’t available. What is the easiest way to convert the collection to a form where I can use these methods?
And more generally, could someone explain to me exactly what the difference is between these two types and the history behind why these methods exist for the newer IEnumerable?
Generally, use
Cast()orOfType(). Both convert a non-genericIEnumerableto a generic one with the specified element type – the difference being how they convert each element.Castwill cast each element, which means it throws an exception if you ask it to perform a conversion it can’t handle.OfTypesimply skips elements which aren’t of the right type.For more information, see the Edulinq blog post about these operators.
As for the difference between the two types – the non-generic one existed before generics, basically, and is therefore not typesafe; the
Currentproperty ofIEnumeratoris justobjectinstead of a specific type. (Additionally,IEnumeratordoesn’t implement IDisposable, whereasIEnumerator<T>does.) If you’re new to generics, that’s more than can easily be covered in an answer here…