[英]Convert comma separated List<string> to List<Int>
I have a List<string>
containing comma separated values, for example, each item looks like "123, 123, 123". 我有一个包含逗号分隔值的
List<string>
,例如,每个项目看起来都像“ 123、123、123”。 Now, I want to convert this to a List<int>
. 现在,我想将其转换为
List<int>
。 How can I do that? 我怎样才能做到这一点?
I have tried the following: 我尝试了以下方法:
List<int> TagIds = parameters.AccidentId.Split(',').Select(int.Parse).ToList();
But It says that: 但它说:
System.Collections.Generic.List does not contain a definition of "Split" accepting a first argument of type 'System.Collections.Generic.List' could be found.
System.Collections.Generic.List不包含“ Split”的定义,该定义接受类型为“ System.Collections.Generic.List”的第一个参数。
I define my AccidentId like this: 我这样定义我的AccidentId:
if (AccidentId != null && AccidentId.itemsSelected != null)
{
parameters.AccidentId = new List<string>();
foreach(var param in AccidentId.itemsSelected)
{
parameters.AccidentId.Add(param);
}
}
You effectively have a list of lists. 您实际上有一个列表列表。 Each
string
in your list is a comma separated list. 列表中的每个
string
都是逗号分隔的列表。
You can use SelectMany
to flatten multiple sequences into a single list. 您可以使用
SelectMany
将多个序列展平为一个列表。
Something like: 就像是:
parameters.AccidentId.SelectMany(s => s.Split(',').Select(int.Parse)).ToList()
This is roughly equivalent to 这大致相当于
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));
}
}
If parameters.AccidentId
is a List<string>
and not a single string
you can't use String.Split
directly. 如果
parameters.AccidentId
是List<string>
而不是单个string
,则不能直接使用String.Split
。 But then you should rename the property anyway, fe AccidentIdList
. 但是,无论如何,您还是应该重命名该属性fe
AccidentIdList
。
You could use this approach: 您可以使用这种方法:
List<int> TagIds = parameters.AccidentId
.SelectMany(id => id.Split(',').Select(int.Parse))
.ToList();
or with Array.ConvertAll
: 或
Array.ConvertAll
:
List<int> TagIds = parameters.AccidentId
.SelectMany(id => Array.ConvertAll(id.Split(','), int.Parse))
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.