将 StringCollection 转换为列表<int>

Cast StringCollection as List<int>

我有一个 StringCollection 对象正在通过一个 ReportParameter 对象传递,我需要让它成为一个 List<int>

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

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

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

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

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

您需要 .Cast<String>() 才能在 StringCollection 上应用 LINQ。