【问题标题】:Cast StringCollection as List<int> [duplicate]将 StringCollection 转换为 List<int> [重复]
【发布时间】:2015-06-11 01:27:32
【问题描述】:

我有一个 StringCollection 对象正在通过 ReportParameter 对象传递,我需要将其改为 List&lt;int&gt;

到目前为止,我已经尝试过了

List<int> ids = (parameters != null) ? parameters[parameters.FindIndex(x => x.Name == "IDs")].Values.Cast<int>().ToList() : null;

它应该检查参数对象是否为空,如果不是,它会找到 IDs 参数的索引,然后尝试将值转换为整数列表。我不断收到Cast is not valid 错误。我将如何将 StringCollection 转换为 List&lt;int&gt;

【问题讨论】:

标签: c# casting


【解决方案1】:

它们是字符串值,您不能将字符串转换为int。你需要Convert/Parse它喜欢:

parameters[parameters.FindIndex(x => x.Name == "IDs")].Values
                     .Cast<String>() //So that LINQ could be applied
                     .Select(int.Parse)
                     .ToList() 

您需要.Cast&lt;String&gt;(),以便您可以在StringCollection 上应用LINQ。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多