DCSIMG
Transform List<T> to List<K> where T inherits from K - Itai Goldstein

Transform List<T> to List<K> where T inherits from K

Download ListExtension.cs file :

Sometimes it is useful to copy one list contents to another which its type is more general.

Let me emphasize my intent with a small example:

Let there be a Dog, Cat & a Mouse types which inherit from Animal type, and let there be some lists: List<Dog>, List<Cat> & List<Mouse> list that we would like to union to one List<Animal> list in order to perform an general operation on all of the animals objects.

Here’s an example of these classes implementation for clarifying purpose:

image

We can try adding the specific lists to the general list (e.g.: adding List<Dog> to List<Animal>):

image

Casting dogs list to List<Animal> is also not allowed.

So we need a way to transform the specific type list to its general type form, something like the following:

image

In order to enable us to perform the precedes we’ll use the Extension Method feature in .NET 3.5 to extend the List<T> type with the Transform method:

image

Note how the Transform method signature enforces T type to inherit from K type using the where keyword.

Summary

In this post I reviewed a way to transform one typed generic list List<T> to another typed generic list List<K> in case that the type T inherits from the type K and used Extension Method feature to add this capability to the List<T> class.

Hope you’ll find it useful.

kick it on DotNetKicks.com

Share it:
Published Sunday, January 25, 2009 9:02 PM by itai

Comments

# re: Transform List<T> to List<K> where T inherits from K

In C# 3.0, with the new extension method, you can do something like this:

myList.Cast<K>().ToList()

Cast is an extension method of Enumerable (don't forget "using System.Linq")

Sunday, January 25, 2009 10:27 PM by Ido Flatow

# re: Transform List<T> to List<K> where T inherits from K

Indeed, Cast can be used to perform this operation as well - but as you mentioned, Cast is available on C# 3.0

Monday, January 26, 2009 9:14 AM by itai

# Transform List

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

Monday, January 26, 2009 10:19 AM by DotNetKicks.com

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: