Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com

Simple way to Convert IEnumerable<Entity> to List<IEntity>

Today I ran into a case where I needed to convert a result set of IEnumerable<Entity> from a Linq2Sql command to a List<IEntity> in order to return the data back to the caller.

We all know that giving the following code public class Entity : IEntity

We can do the following IEntity myEntity = new Entity();

However, we cannot do this IEnumerable<Entity> myEnumerationList = LoadFromLinq.... List<IEntity> myList = myEnumerationList;

The above syntax will cause a runtime exception complaining about invalid cast. In order to convert the list types we have to do it manually. Now there are at least 4 ways that I know of that will do this. I will describe then all here, and give you my take on which one is best.

Lets take a look at the actual code I had that required me to convert the IEnumeration to a List. (BTW, I am returning a List because I do NOT care about update/change notifications that I could get with a Collection).

Finally we are on to our shortest, and most 'elegant' example. This one uses a lambda expression in place of the inline delegate and archives the same result. The only draw back to this method is that if you are not familiar with Lambda's then this solution may be a little off putting.

Of the 4 different ways described above, I like Method 4. However method 3 will get you the exact same result and may be easier to follow for someone who does not know/understand Lambda expressions. If this is the case, then spend the 10 minutes and read up on Lambda's because they are pretty cool and very powerful.