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

守給你的承諾、 提交于 2019-12-07 11:38:50

问题


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.List1[System.Int32]' to type 'System.Collections.Generic.List1[System.String]'.


回答1:


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).



来源:https://stackoverflow.com/questions/28642650/cast-nested-listx-to-nested-listy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!