【发布时间】:2021-10-25 02:17:36
【问题描述】:
任务是:给定一个正整数值序列integerList。 获取仅奇数 integerList 值的字符串表示序列并按升序排序 命令。 这是我的代码:
public static IEnumerable<string> Task5(IEnumerable<int> integerList)
{
var result = from item in integerList
where item % 2 != 0
orderby item descending
select item;
return result.Cast<string>();
}
但我每次尝试开始测试时都会看到此消息:System.InvalidCastException : Unable to cast object of type 'System.Int32' to type 'System.String'。
【问题讨论】:
-
使用
.ToString()方法代替Cast -
这能回答你的问题吗? IEnumerable to string delimited with commas?
-
因为这看起来像是家庭作业,我建议借此机会学习如何阅读错误消息和使用调试器。如果您使用的是 Visual Studio,您可以attach a debugger 并运行代码,它应该会准确地告诉您问题出在哪里:
result.Cast<string>()表达式。然后您可以查找(单击并按 F12)Enumerable.Cast方法,看看它为什么会抛出该异常。 -
你的作业是否提到了如何处理任何重复的 [奇数] 号码?
-
此外,这里的每个答案,包括发布的原始代码,都按 descending 顺序对值进行排序,但任务描述清楚地表明 ascending命令。
descending可能应该从代码中删除
标签: c#