Insert a nested list <X> into a nested list <Y>

I know that it can display a list of elements from one type to another, but how do you insert a nested list into a nested list.

Already tested 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 them give the following error:

Cannot start object of type 'System.Collections.Generic.List 1[System.Int32]' to type 'System.Collections.Generic.List1 [System.String]'.

+4
source share
1 answer

Instead, you can use Select():

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

The reason for this exception: Cast will throw InvalidCastExceptionbecause it is trying to convert List<int>to object, and then apply 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

, . int string.

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

, .


:

Cast<TResult>(this IEnumerable source), :

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);
}

, CastIterator:

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

. foreach object, (TResult).

+3

All Articles