Handy LinQ Extension Methods

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 :-)

3 Comments »

  1. George Tsiokos Said,

    December 5, 2008 @ 2:47 pm

    This won’t be necessary with c# 4.0:

    http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx

  2. Joel Martinez Said,

    December 10, 2008 @ 9:19 am

    Just to follow up on this … George also mentioned via IM that there’s already an existing method called Cast which lets you cast to an existing type … oh well, I had fun writing the code :-P

  3. George Tsiokos Said,

    February 27, 2009 @ 3:24 pm

    This is the problem with Microsoft documentation – it’s hard to find anything! I hope I get around to build that documentation site that makes finding extension methods easier!

RSS feed for comments on this post

Leave a Comment