[英]Cannot convert from 'string' to 'system.collections.generic.list
I struggle with a procedural proggramming exercise.我在程序编程练习中挣扎。 I have to call the method, but when i hover above Consecutive(input) it says:
我必须调用该方法,但是当我在连续(输入)上方的 hover 时,它说:
Cannot convert from 'string' to 'system.collections.generic.list.
无法从“字符串”转换为“system.collections.generic.list”。
I don't know how to bypass this because i frankly don't know how to convert the string to system.collections.generic.list.我不知道如何绕过这个,因为坦率地说,我不知道如何将字符串转换为 system.collections.generic.list。 This is the code i use:
这是我使用的代码:
using System;
using System.Collections.Generic;
namespace HelloWorld
{
internal class Program
{
public static void Main(string[] args)
{
Console.Write("Enter a few numbers (eg 1-2-3-4): ");
var input = Console.ReadLine();
Console.WriteLine(Consecutive(input));
}
public static bool Consecutive(List<int> input)
{
var numbers = new int[input.Count];
input.CopyTo(numbers);
Array.Sort(numbers);
for (var i = 1; i < numbers.Length; i++)
{
if (numbers[i] != numbers[i - 1] + 1)
return false;
}
return true;
}
}
}
Console.ReadLine()
returns string instead of list of integer. You need to convert this string into List and pass it to Consecutive(List<int>)
fucntion Console.ReadLine()
返回字符串而不是 integer 的列表。您需要将此字符串转换为列表并将其传递给Consecutive(List<int>)
函数
...
var input = Console.ReadLine();
//Additional line to convert string to List<string>
var processedInput = Array.ConvertAll(input.Split('-'), int.Parse).ToList();
Console.WriteLine(Consecutive(input));
...
Explanation of conversion of string to List<int>
: string 到
List<int>
的转换说明:
-
as a delimiter.-
作为分隔符。 Array.ConvertAll()
converts IEnumerable<string>
to int. Array.ConvertAll()
将IEnumerable<string>
转换为 int。 .ToList()
convert array of integers to List<int>
. .ToList()
将整数数组转换为List<int>
。 If you want to use TryParse
to parse integer, then you can use out variable feature of C#7.如果你想用
TryParse
解析integer,那么你可以使用C#7的输出变量特性。
//This feature is available from C#7.
//Here if input string fails to parse string to int, it will store 0 as default.
var processedInput = Array.ConvertAll(
input.Split('-'), x => int.TryParse(x, out var i) ? i : 0)
.ToList();
You need to convert String to List,您需要将 String 转换为 List,
var input = Console.ReadLine();
var inputs = input.Split("-").Select(int.Parse).ToList();
Console.WriteLine(Consecutive(inputs));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.