2

I'm trying to use LINQ's cast method to cast an array of strings to an array of integers but getting the error: Specified cast is not valid, what am I doing wrong? Thanks!

string numbers = "1,2,3,4,5";
string[] nums = numbers.Split(',');

try
{
     var ff = nums.Cast<int>().ToArray();
}
catch (Exception ex)
{

}
Flat Eric
  • 7,971
  • 9
  • 36
  • 45
Rauland
  • 2,944
  • 5
  • 34
  • 44

2 Answers2

7

You cannot cast it, you must convert the values:

var ff = nums.Select(x => Convert.ToInt32(x)).ToArray();
Flat Eric
  • 7,971
  • 9
  • 36
  • 45
2

A bit shorter:

var ff = nums.Select(int.Parse).ToArray();
MUG4N
  • 19,377
  • 11
  • 56
  • 83