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)
{

}
1

2 Answers 2

7

You cannot cast it, you must convert the values:

var ff = nums.Select(x => Convert.ToInt32(x)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

2

A bit shorter:

var ff = nums.Select(int.Parse).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.