c# - 将逗号分隔的 List<string> 转换为 List<Int>

标签 c# .net

我有一个 List<string>包含逗号分隔的值,例如,每个项目看起来像“123, 123, 123”。现在,我想将其转换为 List<int> .我该怎么做?

我尝试了以下方法:

List<int> TagIds = parameters.AccidentId.Split(',').Select(int.Parse).ToList();

但是它说:

System.Collections.Generic.List does not contain a definition of "Split" accepting a first argument of type 'System.Collections.Generic.List' could be found.

我这样定义我的 AccidentId:

if (AccidentId != null && AccidentId.itemsSelected != null)
{
    parameters.AccidentId = new List<string>();
    foreach(var param in AccidentId.itemsSelected)
    {
        parameters.AccidentId.Add(param);
    }
}  

最佳答案

您实际上拥有一个列表列表。列表中的每个 string 都是逗号分隔的列表。

您可以使用 SelectMany 将多个序列展平到一个列表中。

类似于:

parameters.AccidentId.SelectMany(s => s.Split(',').Select(int.Parse)).ToList()

这大致相当于

List<int> TagIds = new List<int>();

foreach(string s in parameters.AccidentId)
{
    string[] accidentIds = s.Split(',');
    foreach(string accidentId in accidentIds)
    {
        TagIds.Add(int.Parse(accidentId));
    }
} 

关于c# - 将逗号分隔的 List<string> 转换为 List<Int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934912/

相关文章:

c# - 重载 += 事件运算符

c# - 无法访问注册表 HKLM key

.net - 这两种样式的 xpath 逻辑 'and' 是否等效?

.net - 如何本地化 ASP.NET MVC 应用程序中的 Controller 名称和操作?

c# - OpenCV坐标转换

c# - SQL删除部分字符串

c# - 调整位图图像的大小并使线条更粗

c# - 在 Repeater 中传递行的 ID 以提交 ASP NET 中的按钮

c# - 为什么 System.IO.Path.Combine 有 4 个重载?

c# - 如何找到调用当前方法的方法?