简体   繁体   中英

Converting a string array into a short array

I have a string array to be defined by user input and I need to convert the string array into a short array so I can use the values for calculations. I need to use an array because I will need to refer to all of the values collectively later. This is what I have:

string [] calIntake = new string[3];
calIntake [0] = Console.ReadLine ();
calIntake[1] = Console.ReadLine ();
calIntake[2] = Console.ReadLine ();

I have tried:

short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), Short.Parse);

I get an error with this that says: "The type arguments for method 'System.Array.ConvertAll(TInput[], System.Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Then I tried:

short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), ne Converter<string, short>(Short.Parse));

and I get the same error. So how can I convert a string array based on user input into a short array?

您可以通过short.Parse方法投影字符串:

short[] calIntakeNum = calIntake.Select(short.Parse).ToArray();

calIntake is already an array, you don't need to Split it. There is no type Short in C#, there is short or Int16

short[] calIntakeNum = Array.ConvertAll(calIntake, short.Parse);

The second method you tried failed because you tried calling a method on a class that doesn't exist, and because Short.Parse doesn't exist. Removing the .split(',') from your first parameter to ConvertAll and changing Short.Parse to short.Parse will fix the issue:

short[] calIntakeNum = Array.ConvertAll(calIntake, new Converter<string, short>(short.Parse));

If it's possible for your program, you could declare your array as short[] originally, and call short.Parse on Console.ReadLine() :

short[] shortArray = new short[3];
shortArray[0] = short.Parse(Console.ReadLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM