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!)
- You must include
using System.Linq;
to get this extension method - This casts each item in the list – not the list itself. A new
List<Y>
will be created by the call toToList()
. - This method does not support custom conversion operators. ( see Why does the Linq Cast<> helper not work with the implicit cast operator? )
- This method does not work for an object that has an explicit operator method (framework 4.0)