Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Array does not contain a definition for ToArray

Tags:

c#

asp.net

How can I get this int[] array after the .Split()?

string s = "1,2,3,4";
int[] a = s.Split(',').ToArray<int>();
like image 397
Control Freak Avatar asked Sep 29 '14 08:09

Control Freak


2 Answers

Split doesn't give you magically int values, it returns an array of string. So you'll have to convert.

s.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
like image 175
Raphaël Althaus Avatar answered Nov 10 '22 06:11

Raphaël Althaus


I would do as Raphaël says, but if you are unfamiliar with lambda expressions (the x => .. part) you can use this instead. Both will give you an array of int's, Raphaëls example is to be preferable, but Lambda expressions can be scary when you don't know how they work :P (Basically it means "for each string x, do Convert.ToInt32(x)".

int[] a = s.Split(',').Select(int.Parse).ToArray();
like image 36
Snellface Avatar answered Nov 10 '22 05:11

Snellface