Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



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

private List GetInformation()
{
    IEnumerable results = from sui in DBContextInstance().Table
                                                        select sui;

    return results.ToList().ConvertAll(new Converter(ent => ent));

}

 

Method 1 - Works, but clunky

private List GetInformation()
{
    IEnumerable results = from sui in DBContextInstance().Table
                                                        select sui;

    List returnList = new List();

    foreach (Entity myEntity in results)
    {
        returnList.Add(myEntity);
    }

    return returnList;
}

The above logic works, but is not that great.  The biggest issue I have with this code is it is bloated and mucks up the method.

Method 2 - Better then 1, but still painful

private List GetInformation()
{
    IEnumerable results = from sui in DBContextInstance().Table
                                                        select sui;

    return results.ToList().ConvertAll(new Converter(Convert));
}

// method to do the casting/conversion
private IEntity Convert(Entity entity)
{
    return entity;
}

This method does pretty much the same thing as method 1, but in place of having a loop, the ConvertAll method calls the newly created Convert method during each iteration.

Method 3 - Getting better

private List GetInformation()
{
    IEnumerable results = from sui in DBContextInstance().Table
                                                        select sui;

    return results.ToList().ConvertAll(new Converter(delegate(Entity entity) { return entity; }));
}

This method is nice because all the logic is on one line.  This is the same as method 2, but in place of having to create a new method we are using a inline delegate to do the trick.

Method 4 - Lambda's rock

private List GetInformation()
{
    IEnumerable results = from sui in DBContextInstance().Table
                                                        select sui;

    return results.ToList().ConvertAll(new Converter(ent => ent));
}

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.

Till next time,



Comments

sergiopereira said:

Lambdas are really nice. One other use for the syntax you show is to extract a property from a list of entities. Let's say you have a list of User objects and you need a list of their emails:

List<string> emails = users.ConvertAll<string>( u => u.Email );

# March 28, 2008 3:05 PM

Peter Ritchie said:

If Entity implements IEntity, wouldn't the following do what you want?

return results.Cast<IEntity>().ToList();

# March 28, 2008 4:35 PM

Derik Whittaker said:

@Peter,

You know Peter, you are starting to make me mad.  You always find easier way to solve my issues :).

Yes that did work.

But come on, my Lamba solution is still nice :)

# March 28, 2008 5:06 PM

Edward said:

I'd like to add a slight improvement on the Lambda version:

return results.ToList().ConvertAll(ent => ent);

I like to do away with the explicit delegate constructor.

Well done to Peter for the Cast<> usage.  Comments like this really help while we are all still new to the extensions.  

I hope we a couple more innovative solutions added as comments to this blog post.

# March 28, 2008 5:26 PM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# March 28, 2008 6:06 PM

Dew Drop - March 30, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - March 30, 2008 | Alvin Ashcraft's Morning Dew

# March 30, 2008 5:05 PM

Ruurd Boeke said:

I'm getting irritated with the design of these extensions. I need them to work without prior knowledge of the type I'm casting to. So why didn't they allow this: results.Cast(typeof(myObj))

# April 1, 2008 6:47 AM

Frank La Vigne said:

# April 22, 2008 1:04 PM

Frank La Vigne said:

# April 22, 2008 1:04 PM

Jochen Marczinzik said:

Hi,

why won't this work for you?

IEnumerable<Entity> myEnumerationList = ...

List<IEntity> myList = new List<IEntity>(myEnumerationList);

# July 2, 2008 4:42 AM

Lipitor. said:

Lipitor on cnn. Side effects from lipitor. Lipitor. Nicain and lipitor.

# July 23, 2008 9:10 PM

Valium drug test. said:

Buy valium. Side effects of valium. Valium.

# July 24, 2008 3:58 PM

Rodrigo Almeida said:

Hi, there is an easy way to do this in C# 3.0 (2008)

private List GetInformation()

{

   IEnumerable results = from sui in DBContextInstance().Table select sui;

   return results.ToList<ent>();

}

Or in one line

Hi, there is an easy way to do this in C# 3.0 (2008)

private List GetInformation()

{ return (from sui in DBContextInstance().Table select sui).ToList<ent>(); }

# November 3, 2008 1:47 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News