leora leora - 1 year ago 97
C# Question

In C#, why is this conversion from list of objects to list of interfaces throwing an exception?

In C#, I have a class MyObj that implements an interface IMyInterface.

I now have a collection of lists of MyObj class:

IEnumerable<List<MyObj>> myObjGroups

and I want to convert / cast it to

IEnumerable<List<IMyInterface>> myInterfaceGroups

and everything I have tried has thrown an exception.

An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Collections.Generic.List`1[MyObj]' to type 'System.Collections.Generic.List`1[IMyInterface]'.

I have tried:

IEnumerable<List<IMyInterface>> myInterfaceGroups= new List<List<IMyInterface>>(myObjGroups.Cast<List<IMyInterface>>());


IEnumerable<List<IMyInterface>> myList = myObjGroups.Cast<List<IMyInterface>>();

and both seems to throw exceptions at run time.

Any suggestions on what i am doing wrong?

Answer Source

Try it the following way:

IEnumerable<List<IMyInterface>> myInterfaceGroups = myObjGroups
    .Select(l => l.Select(o => (IMyInterface)o).ToList());

Or if you prefer using the Cast<T>() extension method:

IEnumerable<List<IMyInterface>> myInterfaceGroups = myObjGroups
    .Select(l => l.Cast<IMyInterface>().ToList());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download