将嵌套列表<X>转换为嵌套列表<Y>

4

我知道可以将一个类型的列表转换为另一个类型,但如何将嵌套列表转换为嵌套的 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.List1[System.Int32]”的对象强制转换为类型“System.Collections.Generic.List1[System.String]”。


无论如何,您都不能将int强制转换为string,因此即使您没有嵌套列表,它仍然不起作用。 - Scott Chamberlain
如果您的目的只是更改通用元素的类型,则可以创建一个带有T.ToString()返回值的通用扩展方法。 - Rohit Prakash
1个回答

3
你可以使用Select()代替那种方式:
List<List<String>> new_list = abc.Select(x => x.Select(y=> y.ToString()).ToList()).ToList();

这个异常的原因是: Cast 会抛出 InvalidCastException,因为它试图将 List<int> 转换为 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
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)


你是救星。谢谢! - Daqs
1
非常感谢您提供的详细解释和信息。非常感激。 - Daqs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接