C # Break a string of integers into IEnumerable <int>
I need to convert a whole chain of integers, separated by commas, to a list of integers.
What is the best way to do this?
I can do it below, but worry about performance - is there a more efficient way to do this?
public IEnumerable<int> GetListOfIds() { string Ids = "1,4,5,7,12"; // would be passed into method List<int> _result = Ids.Split(',') .ToList() .Select(item => int.Parse(item)) .ToList(); return _result; } +4
4 answers
There is no need to call ToList , but otherwise your code looks fine:
public IEnumerable<int> GetListOfIds(string ids) { return ids.Split(',').Select(item => int.Parse(item)); } You can also consider adding error handling in case the input string is invalid:
public IEnumerable<int> GetListOfIds(string ids) { foreach (string part in ids.Split(',')) { int x; if (!int.TryParse(part, out x)) { throw new ArgumentException( string.Format("The value {0} cannot be parsed as an integer.", part), "ids"); } else { yield return x; } } } +10
Use nring package for Stringify.Library
Example 1 (the default delimiter is implicitly perceived as a comma)
var ids = "1, 4, 5, 7, 12"; var splitComma = new StringConverter().ConvertTo<List<int>>(ids);Example 2 (delimiter explicitly specified)
var ids = "1; 4; 5; 7; 12";
var splitColon = new StringConverter().ConvertTo<List<int>>(ids, new ConverterOptions { Delimiter = ';' });
0