C#实现字符串长度排序功能报InvalidCastException错误求助
错误原因
你的代码存在两个核心问题,共同触发了类型转换异常:
select item子句返回的是IEnumerable<string>类型的字符串序列,而非需求要求的字符串长度整数序列,序列元素本身是字符串类型,自然无法强制转换为IEnumerable<int>- 排序使用了
descending降序规则,不符合要求的升序排序逻辑
修复后的正确代码
查询表达式写法:
public static IEnumerable<int> Task2(IEnumerable<string> stringList) { var result = from item in stringList orderby item.Length ascending select item.Length; return result; }
更简洁的方法链写法:
public static IEnumerable<int> Task2(IEnumerable<string> stringList) { return stringList.Select(s => s.Length).OrderBy(len => len); }
补充说明
LINQ查询的返回元素类型由select子句的返回值决定,你之前的写法仅按字符串长度排序,但最终返回的还是原字符串序列,C#不支持不同元素类型的泛型集合直接强制转换,因此会抛出InvalidCastException。
内容的提问来源于stack exchange,提问作者Ella
相关产品推荐
相关产品推荐

