gpt4 book ai didi

c# - 将嵌套列表 转换为嵌套列表

转载 作者:太空狗 更新时间:2023-10-30 01:34:51 25 4
gpt4 key购买 nike

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

已经尝试过的解决方案:

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

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

两者都给出以下错误:

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

最佳答案

您可以使用 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

所以,这是不可能的。甚至,你不能投 intstring还有。

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

关于c# - 将嵌套列表<X> 转换为嵌套列表<Y>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28642650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com