Vanessa Kensington
Vanessa Kensington

Reputation: 139

Convert []string to int?

I am trying to store a user input in a list. The user can enter numbers separated by a comma and then I need to perform some action based on the input that's why i am using IF later on and adding the input in a list. However if i try this then i cannot convert []string to int .
I tried to use inputs.Add(Convert.ToInt32(separatedInput)); but i get that i am Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.'

List<int> userDecision = new List<int>();
            Console.WriteLine("enter number separated by comma ");
            var userInputs = Console.ReadLine();
            var separatedInput = userInputs.Split(',');
            var inputs = new List<int>();
            inputs.Add(separatedInput);



            if (input == 1)
            {
                userDecision.Add(1);
            }
            if (input == 2)
            {
                userDecision.Add(2);
            }
            if (input == 3)
            {
                userDecision.Add(3);
            }
            if (input == 4)
            {
                userDecision.Add(4);
            }
            if (input == -1)
            {
                userDecision.Add(-1);
            }

Upvotes: 1

Views: 98

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

You can try using Linq and query userInput into desired List<int> userDecision (let's get rid of temporary separatedInput, input and especially of batch of ifs):

using System.Linq;

...         

Console.WriteLine("enter number separated by comma ");

List<int> userDecision = Console
  .ReadLine()
  .Split(',')
  .Select(item => (success : int.TryParse(item, out int value), 
                     input : value))
  .Where(record => record.success && 
                  (record.input == -1 || record.input >= 1 && record.input <= 4))
  .Select(record => record.input)
  .ToList();     

Upvotes: 1

Jamiec
Jamiec

Reputation: 136174

You can make your list of int by projecting the split string[], using int.Parse and then ToList

var inputs = userInputs.Split(',').Select(int.Parse).ToList();

Note that all the values MUST be parseable to an int, or the above line will fail.

Upvotes: 2

Ajith
Ajith

Reputation: 1545

You need only below line of code.

List<int> userDecision= Array.ConvertAll(Console.ReadLine().Trim().Split(','),int.Parse).ToList<int>();

Upvotes: 1

Related Questions