创建一个大小未知的 C# 数组
本文关键字:未知 数组 一个 创建 | 更新日期: 2023-09-27 17:56:37
可能的重复项:
C# 中长度未知的数组
我想创建一个程序,用户可以在其中输入项目,这些项目将存储在数组中。当用户对项目数量感到满意时,程序将要求每个项目,如果他得到它。
问题是我似乎无法创建一个大小未知的数组。我尝试使用这样的东西:String[] list = new string[]{};
但是当程序到达那里时,它会给出一个IndexOutOfRangeException。
有没有办法做到这一点?
这是完整的代码:
bool groceryListCheck = true;
String[] list = new string[]{};
String item = null;
String yon = null;
int itemscount = 0;
int count = 0;
while (groceryListCheck)
{
Console.WriteLine("What item do you wanna go shop for?");
item = Console.ReadLine();
list[count] = item;
count++;
Console.WriteLine("Done?");
yon = Console.ReadLine();
if (yon == "y")
{
groceryListCheck = false;
itemscount = list.Count();
}
else
{
groceryListCheck = true;
}
}
for (int x = 0; x < itemscount; x++)
{
Console.WriteLine("Did you got the " + list[x] + "?");
Console.ReadKey();
}
使用List
而不是array
。
List<string> myList = new List<string>();
myList.Add("my list item");
收集完所有项后,可以使用foreach
循环循环访问集合中的所有项。
foreach(string listItem in myList)
{
Console.WriteLine(listItem);
}
List<string>
会更容易、更灵活。
这里有很多使用List
的示例,向您展示了从中提取数据的各种方法。
您可以使用
List<string>
,然后,如果需要数组作为结果,则可以调用.ToArray()
方法。
我发现将变量列表制作成列表是有效的。例如:
bool groceryListCheck = true;
List<string> list = new List<string>();
String item = null;
String yon = null;
int itemscount = 0;
while (groceryListCheck)
{
Console.WriteLine("What item do you wanna go shop for?");
item = Console.ReadLine();
list.Add(item);
Console.WriteLine("Done?");
yon = Console.ReadLine();
if (yon == "y")
{
groceryListCheck = false;
itemscount = list.Count();
}
else
{
groceryListCheck = true;
}
}
for (int x = 0; x < itemscount; x++)
{
Console.WriteLine("Did you got the " + list[x] + "?");
Console.ReadKey();
}
这是完整的代码,它对我有用。
我会说为此目的你应该使用哈希表。您可以根据需要添加任意数量,并且无需在创建时指定大小。有点像一个非常简单的数据库。
请参阅:http://www.dotnetperls.com/hashtable