1

Possible Duplicate:
Split string, convert ToList<int>() in one line
Convert comma separated string of ints to int array

I have a string like: string test = "1,2,3,4";

Is there any easier way (syntactically) to convert it to a List<int> equivalent to something like this:

string[] testsplit  = test.Split(',');
List<int> intTest = new List<int>();
foreach(string s in testsplit)
    intTest.Add(int.Parse(s));
Community
  • 1
  • 1
Nemo
  • 4,601
  • 11
  • 43
  • 46

4 Answers4

9

You can throw LINQ at it:

List<int> intTest = test.Split(',').Select(int.Parse).ToList();

It first splits the string, then parses each part(returning an IEnumerable<int>) and finally constructs a list from the integer sequence.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 1
    +1. The only thing I would change is to use a method group rather than lambda. `.Select(int.Parse).ToList()` – J. Holmes Jan 05 '12 at 20:20
  • @32bitkid And you'd leave the explicit type signature? :( Anyway, this will work with the example, but there are fun edge-cases, like "," and ",1", not to mention any invalid int. –  Jan 05 '12 at 20:21
  • @pst I'd consider those cases as invalid input. If you want to handle invalid input you need `TryParse` and the code gets much uglier. – CodesInChaos Jan 05 '12 at 20:24
1
var result = test.Split(',').Select(x => int.Parse(x));

Or, if you really want a List<int> (rather than just any IEnumerable<int>), append a .ToList().

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

test.Split(',').Select(x => int.Parse(x)).ToList()

Andreas
  • 6,447
  • 2
  • 34
  • 46
0

Linq can make it a bit cleaner:

var intTest = test.Split(',').Select(s=>int.Parse(s)).ToList();
Chris Shain
  • 50,833
  • 6
  • 93
  • 125