Handy LinQ Extension Methods

By on 12/5/2008

Isn't it annoying how an IEnumerable<SomeClassThatImplementsISomeInterface>, is not castable to IEnumerable<ISomeInterface> ?  The reasoning for this makes sense once you get into it ... because of generics, those two are functionally different classes.

So, I made a handy-dandy extension method that does the job for me (at the cost of a few more allocations on the heap)

public static IEnumerable<KTo> Convert<TFrom, KTo>(this IEnumerable<TFrom> enumerable)
    where TFrom : KTo
{           
    return enumerable.Select((TFrom s) => (KTo)s);
}

The usage is very simple: return list.Convert<SomeClassThatImplementsISomeInterface, ISomeInterface>();

If you need to do this with an Entity Framework query, where your entities are partial classed to implement an interface ... you need to use this version though:

public static IEnumerable<KTo> ConvertToList<TFrom, KTo>(this IEnumerable<TFrom> enumerable)
    where TFrom : KTo
{           
    return enumerable.ToList().Select((TFrom s) => (KTo)s);
}

note the .ToList() that's injected in there ... the reason for this is that the enumerable needs to be fully enumerated so that the EF executes the query and moves all the results into memory, before doing the cast in the select.

hope that helps :-)

See more in the archives