How to extend arrays in C#

2019-04-19 05:03发布

I have to do an exercise using arrays. The user must enter 3 inputs (each time, information about items) and the inputs will be inserted in the array. Then I must to display the array.

However, I am having a difficult time increasing the array's length without changing the information within it; and how can I allow the user to enter another set of input? This is what I have so far:

public string stockNum;
public string itemName;
public string price;

string[] items = new string[3];

public string [] addItem(string[] items)
{
    System.Console.WriteLine("Please Sir Enter the stock number");
    stockNum = Console.ReadLine();
    items.SetValue(stockNum, 0);
    System.Console.WriteLine("Please Sir Enter the price");
    price = Console.ReadLine();
    items.SetValue(price, 1);
    System.Console.WriteLine("Please Sir Enter the item name");
    itemName = Console.ReadLine();
    items.SetValue(itemName, 2);
    Array.Sort(items);
    return items;
}


public void ShowItem()
{
    addItem(items);
    Console.WriteLine("The stock Number is " + items[0]);
    Console.WriteLine("The Item name is " + items[2]);
    Console.WriteLine("The price " + items[1]);
}

static void Main(string[] args)
{
    DepartmentStore depart = new DepartmentStore();
    string[] ar = new string[3];
    // depart.addItem(ar);
    depart.ShowItem();
}

So my question boils down to:

  1. How can I allow the user to enter more than one batch of input? For example, the first time the user will enter the information about item ( socket number, price and name), but I need to allow the user enter more information about another item?

  2. How can I display the socket num, price and name for each item in the array based on the assumption that I have more than one item in the array?

标签: c# arrays input
10条回答
我命由我不由天
2楼-- · 2019-04-19 05:38

You can use System.Collections.Generic.List<T> which provides a resizable collection which also has a .ToArray() method to return an ordinary array if you need it.

查看更多
贪生不怕死
3楼-- · 2019-04-19 05:42

If you have access to System.Linq then you can use the handy extension method Concat for IEnumerable objects such as arrays. This will allow you to extend an array:

int[] result = new int[] { 1, 2 };
int[] extend = new int[] { 3, 4 };

result = result.Concat(extend).ToArray();

foreach (int i in result)
{
    Console.WriteLine(i.ToString());
}

Result:
1
2
3
4

查看更多
等我变得足够好
4楼-- · 2019-04-19 05:45

Can you use ArrayList instead? It will resize as needed.

查看更多
劳资没心,怎么记你
5楼-- · 2019-04-19 05:48

Use a list, and then convert to an array.

In fact, in this example, you should have a class or struct for StockInfo {stock number, price, item name}, then you should enter the data into a List. Finally, you could convert to StockInfo[] by using the ToArray method of the list.

查看更多
登录 后发表回答