![](/img/trans.png)
[英]LINQ ToDictionary System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.'
[英]System.InvalidCastException : Unable to cast object of type 'System.Linq.OrderedEnumerable`2[System.String,System.Int32]' to type [System.Int32]'
这是任务:给出一个非空字符串序列 stringList。 获取一系列按升序排序的 integer 值,这些值等于 stringList 序列中包含的字符串的长度。 这是我的代码:
public static IEnumerable<int> Task2(IEnumerable<string> stringList)
{
var result = from item in stringList
orderby item.Length descending
select item;
return (IEnumerable<int>)result;
}
但是,当我尝试开始测试时,出现以下消息:System.InvalidCastException: 无法将类型为“System.Linq.OrderedEnumerable 2[System.String,System.Int32]' to type 'System.Collections.Generic.IEnumerable
1[System.Int32]'。 怎么了???
您可以使用方法链接:
stringList.Select(item => item.Length).OrderBy(item => item).AsEnumerable()
您正在选择一个字符串item
,但您的返回类型是一个数字列表。 要使其工作,请将返回类型更改为IEnumerable<string>
public static IEnumerable<string> Task2(IEnumerable<string> stringList)
{
var result = from item in stringList
orderby item.Length descending
select item;
return (IEnumerable<string>)result;
}
或者,如果您需要字符串的长度,则更改 select 以返回长度
public static IEnumerable<int> Task2(IEnumerable<string> stringList)
{
var result = from item in stringList
orderby item.Length descending
select item.Length;
return (IEnumerable<int>)result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.