Is it possible to cast IEnumerable<IEnumerable<T>> to List<List<T>>
? I am getting an invalid cast exception if i do it so.
Thanks
Is it possible to cast IEnumerable<IEnumerable<T>> to List<List<T>>
? I am getting an invalid cast exception if i do it so.
Thanks
The simple cast from a collection to a list is using the ToList()
method. For sample:
var list = collection.ToList();
You could use Linq to get all lists in this structure, for sample:
First import the namespace to use Linq.
using System.Linq;
And try this:
var list = collection.Select(c => c.ToList()) // convert each collection in a list
.Tolist(); //last ToList to get all conversions in a single list
The list
object will be of List<List<T>>
type.
You cannot cast it, you have to use ToList()
to convert the IEnumerable<T>
to List<T>
:
IEnumerable<IEnumerable<T>> input;
var result = input
.Select(i => i.ToList())
.ToList();
Resharper gives a nice suggestion:
var castedList = (myEnum is List<List<T>>) ?
(List<List<T>>) myEnum :
myEnum.Select(x => (x is List<T>) ? x as List<T>: x.ToList())
This will remove the obsolete call to ToList
if the enumeration already IS a list.