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

LINQ处理整数序列报InvalidCastException无法将Int32转String如何解决

错误原因
  • 类型转换逻辑错误:Cast<T>()方法仅支持兼容类型的引用转换、装箱/拆箱转换,不支持自定义类型转换逻辑,int到string不存在此类兼容转换,必须显式调用ToString()方法完成整型到字符串的转换。
  • 排序规则错误:需求要求按升序排序,现有代码中orderby item descending是降序排序,不符合需求。
修复方案

直接在查询表达式的select阶段完成整型到字符串的转换,同时修改排序规则为升序即可,修改后的代码如下:

public static IEnumerable<string> Task5(IEnumerable<int> integerList)
{
    var result = from item in integerList
                 where item % 2 != 0
                 orderby item // 省略ascending,默认就是升序排序
                 select item.ToString();
    return result;
}

如果偏好链式写法,也可以写成如下形式:

public static IEnumerable<string> Task5(IEnumerable<int> integerList)
{
    return integerList
        .Where(item => item % 2 != 0)
        .OrderBy(item => item)
        .Select(item => item.ToString());
}

内容的提问来源于stack exchange,提问作者user16745063

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:09:02