Cast Nested List<X> to Nested List<Y>

c#, casting, list, nested, nested-lists

Solution

You can use `Select()` instead of that way:

List<List<String>> new_list = abc.Select(x => x.Select(y=> y.ToString()).ToList()).ToList();

The reason of this exception: `Cast` will throw `InvalidCastException`, because it tries to convert `List<int>` to `object`, then cast it to `List<string>`:

List<int> myListInt = new List<int> { 5,4};
object myObject = myListInt;
List<string> myListString = (List<string>)myObject; // Exception will be thrown here

So, this is not possible. Even, you can't cast `int` to `string` also.

int myInt = 11;
object myObject = myInt;
string myString = (string)myObject; // Exception will be thrown here

The reason of this exception is, a boxed value can only be unboxed to a variable of the exact same type. Additional Information:

Here is the implemetation of the `Cast<TResult>(this IEnumerable source)` method, if you interested:

public static IEnumerable<TResult> Cast<TResult>(this IEnumerable source) {
    IEnumerable<TResult> typedSource = source as IEnumerable<TResult>;
    if (typedSource != null) return typedSource;
    if (source == null) throw Error.ArgumentNull("source");
    return CastIterator<TResult>(source);
}

As you see, it returns `CastIterator`:

static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source) {
    foreach (object obj in source) yield return (TResult)obj;
}

Look at the above code. It will iterate over source with `foreach` loop, and converts all items to `object`, then to `(TResult)`.

Problem

I know its possible to cast a list of items from one type to another but how do you cast a nested list to nested List . Already tried solutions: ``` List<List<String>> new_list = new List<List<string>>(abc.Cast<List<String>>()); ``` and ``` List<List<String>> new_list = abc.Cast<List<String>>().ToList(); ``` Both of which give the following error: Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Collections.Generic.List`1[System.String]'.

Original source