C# 如何将逗号分隔的字符串转换为 List<int>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9301268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:48:26  来源:igfitidea点击:

How can I convert comma separated string into a List<int>

c#.netstringlist

提问by nacho10f

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

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

This doesn't work cause the split method returns a string[]

这不起作用,因为 split 方法返回一个 string[]

采纳答案by dasblinkenlight

Here is one way of doing it:

这是一种方法:

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

回答by Justin Niessner

You can use LINQ w/ int.Parse()to convert the string[]to an IEnumerable<int>and then pass that result to the List<T>constructor:

您可以使用 LINQ w/int.Parse()将 转换string[]为 an IEnumerable<int>,然后将该结果传递给List<T>构造函数:

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

回答by Oybek

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

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

回答by Henk Holterman

A little LINQ goes a long way:

一点 LINQ 大有帮助:

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

回答by Agustin Meriles

If you are using C# 3.5 you can use Linq to achieve this

如果您使用的是 C# 3.5,您可以使用 Linq 来实现这一点

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

or the short one

或短的

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

回答by LiquidPony

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

回答by LiquidPony

Without LINQ Query , you can choose this method ,

如果没有 LINQ Query ,您可以选择这种方法,

string tags = "9,3,12,43,2";
List<string> numbers = nos.Split(',').ToList<string>();

and then you can convert this List into integer type...

然后您可以将此列表转换为整数类型...

回答by khalid13

If you want to include some simple validation and skip over invalid values (instead of throwing an exception), here's something that uses TryParse:

如果你想包含一些简单的验证并跳过无效值(而不是抛出异常),这里有一些使用 TryParse 的东西:

string csv = "1,2,3,4,a,5";
int mos = 0;
var intList = csv.Split(',')
                    .Select(m => { int.TryParse(m, out mos); return mos; })
                    .Where(m => m != 0)
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5

EDIT:Here is an updated query based on feedback by Antoine. It calls TryParse first to filter out any bad values, and then Parse to do the actual conversion.

编辑:这是基于 Antoine 反馈的更新查询。它首先调用 TryParse 来过滤掉任何错误的值,然后调用 Parse 来进行实际的转换。

string csv = "1,2,3,4,a,5,0,3,r,5";
int mos = 0;
var intList = csv.Split(',')
                    .Where(m => int.TryParse(m, out mos))
                    .Select(m => int.Parse(m))
                    .ToList();

//returns a list with integers: 1, 2, 3, 4, 5, 0, 3, 5

Edit 2:An updated query for C# 7.0, thanks to feedback from Charles Burns. Note that we get rid of the extra mos variable with this approach, so it's a bit cleaner.

编辑 2:C# 7.0 的更新查询,感谢 Charles Burns 的反馈。请注意,我们用这种方法去掉了额外的 mos 变量,所以它更简洁一些。

string csv = "1,2,3,4,a,5,0,3,r,5";
var intList = csv.Split(',')
                 .Where(m => int.TryParse(m, out _))
                 .Select(m => int.Parse(m))
                 .ToList();

回答by SolidSnake4444

I made a modification to khalid13's answer. If the user put a string of "0", his answer would remove that from the resulting list. I did something similar but used an anonymous object.

我对 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 is a custom function I made that protects if the string is null.

TrimNullProtection 是我制作的一个自定义函数,用于保护字符串是否为空。

What the above does is strip out any strings that were not able to be converted with no error. If you need to error if there was a problem with the conversion, then the accepted answer should do the trick.

上面所做的是去除任何无法正确转换的字符串。如果您需要在转换出现问题时出错,那么接受的答案应该可以解决问题。

回答by drchanix

I stumbled upon this and I just want to share my own solution without linq. This is a primitive approach. Non-integer values will not be added in the list also.

我偶然发现了这一点,我只想在没有 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);
    }
}

Hope this helps.

希望这可以帮助。