【问题标题】:Cast Nested List<X> to Nested List<Y>将嵌套列表<X> 转换为嵌套列表<Y>
【发布时间】:2015-02-21 05:55:22
【问题描述】:

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

已经尝试过的解决方案:

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

【问题讨论】:

  • 无论如何,您都不能将int 转换为string,因此即使您没有嵌套列表,它仍然无法正常工作。
  • 如果你的目的只是要改变泛型元素的类型,你可以创建一个泛型扩展方法,返回值为 T.ToString()

标签: c# list casting nested nested-lists


【解决方案1】:

您可以使用Select() 代替这种方式:

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

这个异常的原因:Cast会抛出InvalidCastException,因为它试图将List&lt;int&gt;转换为object,然后再转换为@ 987654328@:

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&lt;TResult&gt;(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)

【讨论】:

  • 你是救生员。谢谢!
  • 非常感谢您的详细解释/信息。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2018-11-12
  • 2016-02-08
  • 2021-06-09
  • 1970-01-01
相关资源
最近更新 更多