How can I convert comma separated string into a List

前端 未结 11 2161
我寻月下人不归
我寻月下人不归 2020-12-07 09:16
string tags = \"9,3,12,43,2\"

List TagIds = tags.Split(\',\');

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

11条回答
  •  醉话见心
    2020-12-07 10:02

    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.

    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.

    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.

提交回复
热议问题