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条回答
Evening l夕情丶
2楼-- · 2019-04-19 05:28

In .NET (C#), an array isn't resizable. It's not like in JavaScript or PHP were an array is made very flexible and can be extend with arbitrary elements.

Per definition an default static array has a fix size, so you can reference an element within by using the index. ( http://en.wikipedia.org/wiki/Array_data_structure#Array_resizing ) But there you can read about dynamic array. In C# it will be the System.Collections.ArrayList-Object. ( http://en.wikipedia.org/wiki/Dynamic_array )

So what you need is either the ArrayList-Definition or a normal list or generic list. (System.Collections.Generic.List)

string[] items = new string[3] { "input1", "input2", "input3" };
string[] moreItems = new string[10] { "input4", "input5" };

// array to list
List<string> itemsList = items.ToList<string>();

itemsList.Add("newItem");
// or merge an other array to the list
itemsList.AddRange(moreItems);

// list to array
string[] newArray = itemsList.ToArray();
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-19 05:28

I think you may be going about the problem wrong...

Consider that the three items (stock number, price, and name) are part of a larger object. For now we can just call it item. We want to store a number of items in a list or array. Consider using an object-oriented approach like this:

class Widget
{
  public int StockNum;
  public int Price;
  public string Name;

  Widget(stockNum, price, name)
  {
    this.StockNum= stockNum;
    this.Price = price;
    this.Name = name;
  }
}

Now, you can can instantiate a list of these objects:

List<Widget> items = new List<Widget>();

And add items to them:

for (int i = 0; i < 5; i++)
{
  //Get input from user
  System.Console.WriteLine("Please Sir Enter the stock number");
  stockNum= Convert.ToInt32(Console.ReadLine()); //This isn't very safe...

  System.Console.WriteLine("Please Sir Enter the price");
  price = Convert.ToInt32(Console.ReadLine()); //This isn't very safe...

  System.Console.WriteLine("Please Sir Enter the item name");
  name = Console.ReadLine();

  //Then add it to a new object
  Widget item = new Widget(stockNum, price, name);

  //And add this item to a list
  items.Add(item);
}
查看更多
放荡不羁爱自由
4楼-- · 2019-04-19 05:29

Assuming your assignment requires you to use Arrays and not other collection classes, then you will have to do things the hard way.

Arrays are immutable, that is you cannot change them after they have been created. You can change the contents, but not the size of the array. If you need to grow or shrink the array, you will have to create a new array with the new number of items, then copy the items you want from the old array to the new array.

For instance, suppose you want to take an array and only copy the even elements.

int[] a = new int[] {0,1,2,3,4,5,6,7,8,9};
int[] a2 = new int[a.Length / 2];
int counter = 0;
for (int i = 0; i < a.Length; i = i + 2)
{
    a2[counter++] = a[i];
}

Then, you could always assign a2 back to a

a = a2;
查看更多
Deceive 欺骗
5楼-- · 2019-04-19 05:29

I've had the same problem but could not change the type and had to stuck with Array since I was extending an existent API class. Here's a simple template method that extends an existent array:

    public static T[] ExtendArray<T> ( T[] array , uint index) where T:new()
    {
        List<T> list = new List<T>();
        list.AddRange(array);

        while (list.Count < index) {
            list.Add(new T());
        }

        return list.ToArray();
    }

Please note that the above also initializes the elements with the default constructor.

查看更多
不美不萌又怎样
6楼-- · 2019-04-19 05:35

Starting with .NET Framework 3.5, for one-dimensional arrays you can use Array.Resize<T> method:

int[] myArray = { 1, 2, 3 };
Array.Resize(ref myArray, 5);

MSDN link is here.

查看更多
仙女界的扛把子
7楼-- · 2019-04-19 05:36

You could work around the 'problem' of not being able to resize arrays by using an array that is as big as the biggest array you expect to have. Note that this is considered hacking, not structured programming!

查看更多
登录 后发表回答