System.InvalidCastException: 无法将类型'System.Linq.OrderedEnumerable`2[System.String,System.Int32]'的对象



任务如下:给定一个非空字符串序列stringList。获取一个升序排序的整数值序列,该序列等于所包含字符串的长度在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.OrderedEnumerable2[System.String,System.Int32]' to type 'System.Collections.Generic.IEnumerable[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;
}

相关内容

最新更新