如何在 C# 中扩展数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/628427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:55:25  来源:igfitidea点击:

How to extend arrays in C#

c#arraysinput

提问by 3yoon af

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.

我必须使用数组做一个练习。用户必须输入 3 个输入(每次都是关于项目的信息),这些输入将被插入到数组中。然后我必须显示数组。

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?

  1. 如何允许用户输入多于一批的输入?例如,用户第一次将输入有关物品的信息(插座编号、价格和名称),但我需要让用户输入有关另一物品的更多信息?

  2. 基于数组中有多个项目的假设,如何显示数组中每个项目的套接字编号、价格和名称?

采纳答案by algorhythm

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.

在 .NET (C#) 中,数组不可调整大小。它不像在 JavaScript 或 PHP 中那样,数组非常灵活并且可以使用任意元素进行扩展。

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)

根据定义,默认静态数组具有固定大小,因此您可以使用索引引用其中的元素。(http://en.wikipedia.org/wiki/Array_data_structure#Array_resizing)但是您可以在那里阅读有关动态数组的信息。在 C# 中,它将是 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)

因此,您需要的是 ArrayList-Definition 或普通列表或通用列表。(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();

回答by Matthew Dresser

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.

您可以使用System.Collections.Generic.List<T>它提供一个可调整大小的集合,.ToArray()如果需要,该集合还有一个返回普通数组的方法。

回答by Chris Ballance

Can you use ArrayListinstead? It will resize as needed.

你可以用ArrayList代替吗?它将根据需要调整大小。

回答by John Saunders

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.

事实上,在这个例子中,你应该有一个 StockInfo {stock number, price, item name} 的类或结构,然后你应该将数据输入到一个列表中。最后,您可以使用列表的 ToArray 方法转换为 StockInfo[]。

回答by Andrew Flanagan

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:

考虑三个项目(库存编号、价格和名称)是一个更大对象的一部分。现在我们可以称之为item。我们想item在列表或数组中存储许多s。考虑使用这样的面向对象的方法:

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

回答by Erik Funkenbusch

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

然后,您始终可以将 a2 分配回 a

a = a2;

回答by tozevv

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:

我遇到了同样的问题,但无法更改类型并且不得不坚持使用 Array,因为我正在扩展现有的 API 类。这是一个扩展现有数组的简单模板方法:

    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 initializesthe elements with the default constructor.

请注意,上面还使用默认构造函数初始化元素。

回答by Sebastiaan M

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!

您可以通过使用与您期望拥有的最大数组一样大的数组来解决无法调整数组大小的“问题”。请注意,这被认为是黑客行为,而不是结构化编程!

回答by ruhler

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

如果您有权访问 System.Linq,那么您可以将方便的扩展方法Concat用于 IEnumerable 对象,例如数组。这将允许您扩展数组:

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

结果:
1
2
3
4

回答by Nenad

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

从 .NET Framework 3.5 开始,对于一维数组,您可以使用Array.Resize<T>方法:

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

MSDN link is here.

MSDN 链接在这里