Shorter syntax for casting from a List<X> to a List<Y>?

Jimbo picture Jimbo · Feb 25, 2011 · Viewed 173.5k times · Source

I know its possible to cast a list of items from one type to another (given that your object has a public static explicit operator method to do the casting) one at a time as follows:

List<Y> ListOfY = new List<Y>();

foreach(X x in ListOfX)
    ListOfY.Add((Y)x);

But is it not possible to cast the entire list at one time? For example,

ListOfY = (List<Y>)ListOfX;

Answer

Jamiec picture Jamiec · Feb 25, 2011

If X can really be cast to Y you should be able to use

List<Y> listOfY = listOfX.Cast<Y>().ToList();

Some things to be aware of (H/T to commenters!)