Reputation: 3677
I have PInfo2[] pInfo
and need to use it as an IEnumerable<PInfo3> betterInfo
where public class PInfo3 : PInfo2
What I've tried, but doesn't work:
(IEnumerable<PInfo3>)pInfo //Runtime error: "Unable to cast object of type 'PInfo2[]' to type 'System.Collections.Generic.IEnumerable`1[
IEnumerable<PInfo3> betterInfo = pInfo as IEnumerable<PInfo3>; //Always null after cast.
What am I doing wrong, aka how am I being dumb? Do I need to for-loop through the array? I don't know why but I was hoping I didn't have to do that.
Upvotes: 0
Views: 299
Reputation: 12805
You can use LINQ to cast the objects of the enumeration to a different related type.
pInfo.Cast<PInfo3>();
Now, this can cause some issues if there are some elements in the collection that can't be cast, but there are ways around that as well (see Edit):
pInfo.Select(p => (PInfo3)p).Where(p => p != null);
The Cast
should be used when you know that the conversion will succeed, and the second when there could be elements that can't make the conversion.
EDIT
Per Daniel A. White's comment below, there is also the .OfType<T>()
method, which will only get the items that match the requested type, and avoid the IllegalCastException
that Cast<T>()
will throw.
For additional details, see this answer.
Upvotes: 1