将嵌套列表<x>转换为嵌套列表<y> </y> </x>

时间:2015-02-21 05:55:22

标签: c# list casting nested nested-lists

我知道可以将一个项目列表从一种类型转换为另一种类型但是如何将嵌套列表转换为嵌套List。

已经尝试过的解决方案:

List<List<String>> new_list = new List<List<string>>(abc.Cast<List<String>>());

List<List<String>> new_list = abc.Cast<List<String>>().ToList();

两者都会出现以下错误:

  

无法投射类型的对象   'System.Collections.Generic.List 1[System.Int32]' to type 'System.Collections.Generic.List 1 [System.String]'。

1 个答案:

答案 0 :(得分:3)

您可以使用Select()代替:

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

此异常的原因: Cast会抛出InvalidCastException,因为它会尝试将List<int>转换为{{1}然后将其转换为object

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

此异常的原因是, 盒装值 只能取消装入 完全相同类型 <的变量/ strong>即可。


其他信息:

以下是Cast<TResult>(this IEnumerable source)方法的实现,如果您感兴趣:

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

如您所见,它返回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