0

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.

gakera
  • 3,589
  • 4
  • 30
  • 36
  • 4
    try `pInfo.Cast()`. That is in the `System.Linq` namespace, in case you don't have it in your file. – krillgar Mar 03 '15 at 17:18
  • 2
    Please show a short but *complete* program demonstrating the problem... and clarify what you want to happen if there are non-`PInfo3` items in the collection. – Jon Skeet Mar 03 '15 at 17:19
  • @krillgar cool, that totally works, thanks :) I knew I was being a dumbass. – gakera Mar 03 '15 at 17:22
  • Sooo... etiquette question, do I provide an answer to my own question here then or? I know I can, but should I? – gakera Mar 03 '15 at 17:23
  • @krillgar Are you going to post that as an answer? It is the right one. OP, etiquette is to ask the user to post it as an answer. – BradleyDotNET Mar 03 '15 at 17:32
  • Failing that, edit your question to make it clear that you have an answer (and state what the answer is), so people reading this question know it's been answered without reading the comments. – Wai Ha Lee Mar 03 '15 at 17:48
  • Sorry @BradleyDotNET , got called away to lunch. – krillgar Mar 03 '15 at 18:02

1 Answers1

1

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.

Community
  • 1
  • 1
krillgar
  • 12,596
  • 6
  • 50
  • 86