string tags = "9,3,12,43,2"

List<int> TagIds = tags.Split(',');

这行不通,因为split方法返回一个字符串[]


当前回答

我偶然发现了这个,我只是想分享我自己的解决方案没有linq。这是一种原始方法。非整数值也不会被添加到列表中。

List<int> TagIds = new List<int>();
string[] split = tags.Split(',');
foreach (string item in split)
{
    int val = 0;
    if (int.TryParse(item, out val) == true)
    {
        TagIds.Add(val);
    }
}

希望这能有所帮助。

其他回答

string tags = "9,3,12,43,2";
List<int> TagIds = tags.Split(',').Select(int.Parse).ToList();

我偶然发现了这个,我只是想分享我自己的解决方案没有linq。这是一种原始方法。非整数值也不会被添加到列表中。

List<int> TagIds = new List<int>();
string[] split = tags.Split(',');
foreach (string item in split)
{
    int val = 0;
    if (int.TryParse(item, out val) == true)
    {
        TagIds.Add(val);
    }
}

希望这能有所帮助。

有一点LINQ可以走很长的路:

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

我修改了khalid13的答案。如果用户输入一个字符串“0”,他的回答将从结果列表中删除该字符串。我做了类似的事情,但使用了匿名对象。

var result = commaSeparatedString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(s => new { didConvert = int.TryParse(s.TrimNullProtection(), out convertedInt), convertedValue = convertedInt })
            .Where(w => w.didConvert)
            .Select(s => s.convertedValue)
            .ToList();

TrimNullProtection是一个自定义函数,我做了保护,如果字符串为空。

上面所做的是剔除任何不能正确转换的字符串。如果转换存在问题,则需要报错,那么接受的答案应该是有用的。

你可以使用LINQ w/ int. parse()将字符串[]转换为IEnumerable<int>,然后将结果传递给List<T>构造函数:

var tagIds = new List<int>(tags.Split(',').Select(s => int.Parse(s)));