0

Possible Duplicate:
Split string, convert ToList<int>() in one line…

i have a string that looks like this.

string s = "1,6,4,3,5,7,4";

and i want to convert this into an array of integers.

what is the best and fastest way of doing this in C#?

Community
  • 1
  • 1
leora
  • 188,729
  • 360
  • 878
  • 1,366
  • 1
    I don't know about fastest, but in C#4, a terse way would be: `var nums = Array.ConvertAll(s.Split(','), int.Parse);` – Ani Feb 22 '11 at 06:00
  • @jleedev, technically, the dup doesn't address converting it to an *array*. But...the OP can just tack on `.ToArray()`. – Kirk Woll Feb 22 '11 at 06:01

2 Answers2

8

use split method.

int[] array = s.Split(',').Select(str => int.Parse(str)).ToArray();

Hmm, don't know if it is fastest way, however it is the simplest way :)

Danil
  • 1,883
  • 1
  • 21
  • 22
0

Hope this helps :)

int[] i = Array.ConvertAll(s.Split(','), new Converter<string, int>(delegate (string str) { return int.Parse(str); } ));
PedroC88
  • 3,708
  • 7
  • 43
  • 77