You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 05:36:01