开发者

List Collection in C# - adding values from command prompt

I am trying to learn a little more about the List Collection and am able to get it to function when the values are added statically. List.Add(value1), but when I make it a string and try to accept data in an undefined arrary, I run into trouble and am not sure which steps to take to fix it. Can someone shed light?

Below is my Code. Than开发者_如何学JAVAks.

class Program
{
    static void Main()
    {

        List<string> list = new List<string>();

        for (int i = 0; i < 5; i++)
        {
            List<string> listS = new List<string>();
            Console.WriteLine("Please enter a number");
            listS.Add(listS) = Console.ReadLine();
        }

    }
}


class Program
{
    static void Main()
    {

        List<string> list = new List<string>();

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Please enter a number");
            list.Add(Console.ReadLine()); // HERE !!
        }

    }
}


I think this is what you are looking for... You want to pass the string that you want to add to the collection as the parameter to the Add function.

Cheers.

List<string> list = new List<string>();

    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine("Please enter a number");
        list.Add(Console.ReadLine());
    }


I think you're looking for

lists.Add(Console.ReadLine());

Right now, you're trying to add the list to itself...


Just replace:

listS.Add(listS) = Console.ReadLine();

with:

listS.Add(Console.ReadLine());

how does it work now?


Replace

listS.Add(listS) = Console.ReadLine();

With

listS.Add(Console.ReadLine());


Use this:

list.Add(Console.ReadLine());


When using Console.ReadLine it returns a string.

Changing your code to

    for (int i = 0; i < 5; i++)
{

    Console.WriteLine("Please enter a number");
    string listS = Console.ReadLine();
    //avoid problems with empty or nullstrings
    if(!String.IsNullOrEmpty(listS))
    {
      list.Add(listS);
    }
}

would add your input to the list.

If you want to add multiple arguments through console you need to parse the string, though

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜