简体   繁体   中英

How do I get my IEnumerable<T> extension methods on an IEnumerable?

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() or OfType() . Both convert a non-generic IEnumerable to a generic one with the specified element type - the difference being how they convert each element. Cast will cast each element, which means it throws an exception if you ask it to perform a conversion it can't handle. OfType simply 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 Current property of IEnumerator is just object instead of a specific type. (Additionally, IEnumerator doesn't implement IDisposable, whereas IEnumerator<T> does.) If you're new to generics, that's more than can easily be covered in an answer here...

To go from IEnumerable to an IEnumerable<T> you could use either the Cast<T>() or the OfType<T> .

As far as why there are two. IEnumerable existed since initial .NET 1.0 days. Although the CLR internally supported typed collections, they were not exposed in C# (or VB.NET). So when they were exposed the System.Collections.Generics namespace was added with IEnumerable<T> .

The IEnumerable interface already existed before generic collections from the System.Collections.Generic namespace, including IEnumerable<T> , were added to the .NET Framework 2.0.

You can cast your non-generic collection to a generic one using the MakeGeneric() extension method:

public static class EnumerableExtensions
{
    public static IEnumerable<object> MakeGeneric(this IEnumerable nonGenericCollection)
    {
        return nonGeneric.Cast<object>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM