8

可能重复:
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();
        }
4

5 回答 5

15

使用 aList而不是array.

List<string> myList = new List<string>();
myList.Add("my list item");

收集完所有项目后,您可以使用foreach循环遍历集合中的所有项目。

foreach(string listItem in myList)
{
    Console.WriteLine(listItem);
}
于 2013-01-30T16:26:24.647 回答
5

AList<string>会更容易和更灵活。

List 这里有很多使用 a 的示例,向您展示了从中提取数据的各种方法。

于 2013-01-30T16:27:02.787 回答
4

您可以使用 aList<string>然后,如果您需要一个数组作为结果,您可以调用该.ToArray()方法。

于 2013-01-30T16:28:08.810 回答
1

我发现将变量列表变成列表是有效的。例如:

        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();
        }

那是完整的代码,它对我有用。

于 2013-01-30T16:35:01.947 回答
0

为此,我会说您应该使用Hashtable。您可以根据需要添加到它,并且在创建它时不需要指定大小。有点像一个非常简单的数据库。

见: http: //www.dotnetperls.com/hashtable

于 2013-01-30T16:28:15.110 回答