Click here to Skip to main content
15,558,352 members
Articles / Programming Languages / C# 4.0
Posted 6 Sep 2010

Tagged as


5 bookmarked

Generic List Conversion

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
6 Sep 2010CPOL
How to convert a generic List of derived types to a generic list of base types.

The Scenario

You have a base class Mammal and a derived class Dog.

public abstract class Mammal

public class Dog : Mammal

You create a list of dogs List<Dog>.

The Problem

You want to have a list of mammals List<Mammal> that is built from the list of dogs. If you try either an implicit or explicit cast you will be told that it isn't possible!

The Solution

This little function will create a list of mammals from a list of dogs.

public static List<TBase> DerivedConverter<TBase, TDerived>(List<TDerived> derivedList)
    where TDerived : TBase
    return derivedList.ConvertAll<TBase>(
       new Converter<TDerived, TBase>(delegate(TDerived derived)
           return derived;

To use it:

List<Base> listBase = DerivedConverter<Base, Derived>(listDerived);

In our scenario Base would be Mammal and Derived would be Dog.

You could use the same function for Human, Dolphin, Cat etc, or any other derived class list to base class list without having to write a new converter.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
CEO Dave Meadowcroft
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralReason for my vote of 5 Thank you! Nice tip! Pin
Simon Dufour7-Sep-10 3:41
Simon Dufour7-Sep-10 3:41 
GeneralGood job! The DerivedConverter method could be a bit simple... Pin
Kubajzz6-Sep-10 3:04
Kubajzz6-Sep-10 3:04 
Good job!

The DerivedConverter method could be a bit simpler using lambda expression syntax:

return derivedList.ConvertAll<TBase>(
new Converter<tderived, tbase="">(item => item)

Or even simpler using Linq:

return derivedList.Cast<TBase>().ToList();

I guess it's just the matter of personal preference...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.