WDTBD: Linq Cast

Linq supplies a Cast option. It can be used in case you have a list with object A that must be converted to a list of object B, where object B inherits of object A. You don’t have to write a foreach or map objects anymore.

Assume you have two objects:

Class A{ [properties]}
Class B: A {}

ListWithObjectA must be converted to ListWithObjectB

var listWithObjectA = GetListWithObjectA();
var listWithObjectB = new List<B>();
foreach(var a in listWithObjectA)
{
 var b= new B();
 b.property == a.property;
 listWithObjectB.Add(b)
}

With Linq.cast:

var listWithObjectA = GetListWithObjectA();
var listWithObjectB = listWithObjectA.Cast<B>(listWithObjectA).ToList();

However, if one object in the original list cannot be cast it throws an InvalidCastException().

That can be solved by using OfType

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s