1

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

Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156

3 Answers3

9

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.

Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
3

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();
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
1

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.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • Now you don't do the same thing if you have a List> as you do if you have an IEnumerable>. In the first case you return a reference to the lists while in the second you make new lists. Only doing the myEnum.Select(x => x.ToList()).ToList() will make new copies of everything. – Rune Grimstad Jan 08 '16 at 12:06
  • @RuneGrimstad As far as I understand we do not need new lists, if the enumerations within already are lists we can take new references to them instead, why create new list? – MakePeaceGreatAgain Jan 08 '16 at 12:16
  • I agree. My point was that the two paths would do different things. In one case you get references while in the other you get new lists – Rune Grimstad Jan 08 '16 at 13:25