Reputation: 134
I have this exercise. I don't know what the problem is, but I keep getting the error - can someone help me what is wrong please?
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.String[]' to type 'System.IConvertible'.
at System.Convert.ToInt32(Object value)
at exercise_4.Program.Main(String[] args) in D:\Courses\c#\beginner\visual studio\section 6 exercises\exercise 4\exercise 4\Program.cs:line 20
This is what is written in my console
Write a program and ask the user to supply a list of comma separated numbers (e.g 5, 1, 9, 2, 10). If the list is empty or includes less than 5 numbers, display "Invalid List" and ask the user to re-try; otherwise, display the 3 smallest numbers in the list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace exercise_4
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("write numbers seperated with coma");
var numbers = new List<int>();
var input = (Console.ReadLine());
var value = input.Split(',');
var conv =Convert.ToInt32(value);
numbers.Add(conv);
if (value.Length < 5)
{
Console.WriteLine("invalid list!! retry");
continue;
}
else
{
numbers.Sort();
Console.WriteLine(numbers[0] , numbers[1], numbers [2]);
}
}
}
}
}
Thanks for answers.
Upvotes: 1
Views: 2636
Reputation: 183
You can replace this:
var values = input.Split(',');
to this:
var values = input.Split(',').Select(a => int.Parse(a)).OrderBy(a => a).Take(3);
It'll give you three smallest numbers.
Upvotes: 2
Reputation: 2613
Split method returns an array of strings. The exception is thrown because the following statement tries to cast the string[] to int:
var conv =Convert.ToInt32(value);
You should iterate and parse each item in the array as follows:
while (true)
{
Console.WriteLine("write numbers seperated with coma");
List<int> numbers = new List<int>();
var input = (Console.ReadLine());
var values = input.Split(',');
foreach (var value in values)
{
int number;
// If the input can be parsed to int, add it to numbers list.
if (int.TryParse(value, out number))
{
numbers.Add(number);
}
}
if (numbers.Count < 5)
{
Console.WriteLine("invalid list!! retry");
continue;
}
else
{
numbers.Sort();
numbers.Take(3)
.ToList()
.ForEach(number => Console.WriteLine(number));
}
}
Upvotes: 2