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
source share
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
source

You can at least omit the first ToList () operator, so it will

  List<int> _result = Ids.Split(',').Select(item => int.Parse(item)).ToList(); 
+1
source

Perhaps you can loop through the result of split and return yield int.Parse ... but I would not expect much difference if you really have a lot of elements in the source string.

0
source

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
source

All Articles