将值添加到 C# 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/202813/
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-03 17:51:02  来源:igfitidea点击:

Adding values to a C# array

c#arrays

提问by Ross

Probably a really simple one this - I'm starting out with C# and need to add values to an array, for example:

可能是一个非常简单的 - 我从 C# 开始,需要向数组添加值,例如:

int[] terms;

for(int runs = 0; runs < 400; runs++)
{
    terms[] = runs;
}

For those who have used PHP, here's what I'm trying to do in C#:

对于那些使用过 PHP 的人,这是我在 C# 中尝试做的事情:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}

采纳答案by Tamas Czinege

You can do this way -

你可以这样做——

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.

或者,您可以使用列表 - 列表的优点是,在实例化列表时您不需要知道数组大小。

List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsList.Add(value);
}

// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();

Edit:a) forloops on List<T> are a bit more than 2 times cheaper than foreachloops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using foris 5 times cheaper than looping on List<T> using foreach(which most of us do).

编辑:a) List<T> 上的for循环比 List<T> 上的foreach循环便宜 2 倍多,b) 数组循环比 List<T> 上循环便宜约 2 倍,c) 循环使用for 的数组比使用foreach(我们大多数人都这样做)在 List<T> 上循环便宜 5 倍。

回答by Motti

You have to allocate the array first:

您必须先分配数组:

int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}

回答by Johnno Nolan

int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

回答by JB King

int ArraySize = 400;

int[] terms = new int[ArraySize];


for(int runs = 0; runs < ArraySize; runs++)
{

    terms[runs] = runs;

}

That would be how I'd code it.

那将是我编码的方式。

回答by Michael Stum

You can't just add an element to an array easily. You can set the element at a given position as fallen888outlined, but I recommend to use a List<int>or a Collection<int>instead, and use ToArray()if you need it converted into an array.

您不能简单地将元素添加到数组中。您可以在给定位置设置元素,如fall888概述,但我建议使用 aList<int>或 aCollection<int>代替,并ToArray()在需要将其转换为数组时使用。

回答by Jimmy

C# arrays are fixed length and always indexed. Go with Motti's solution:

C# 数组是固定长度的,并且总是索引的。使用 Motti 的解决方案:

int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.

请注意,此数组是一个密集数组,是一个 400 字节的连续块,您可以在其中放置内容。如果您想要一个动态大小的数组,请使用 List<int>。

List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
    terms.Add(runs);
}

Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.

int[] 和 List<int> 都不是关联数组——这将是 C# 中的 Dictionary<>。数组和列表都是密集的。

回答by FlySwat

Answers on how to do it using an array are provided here.

此处提供了有关如何使用数组执行此操作的答案。

However, C# has a very handy thing called System.Collections :)

然而,C# 有一个非常方便的东西叫做 System.Collections :)

Collections are fancy alternatives to using an array, though many of them use an array internally.

集合是使用数组的奇特替代品,尽管其中许多在内部使用数组。

For example, C# has a collection called List that functions very similar to the PHP array.

例如,C# 有一个名为 List 的集合,其功能与 PHP 数组非常相似。

using System.Collections.Generic;

// Create a List, and it can only contain integers.
List<int> list = new List<int>();

for (int i = 0; i < 400; i++)
{
   list.Add(i);
}

回答by David Mitchell

If you're writing in C# 3, you can do it with a one-liner:

如果您使用 C# 3 编写,则可以使用单行代码:

int[] terms = Enumerable.Range(0, 400).ToArray();

This code snippet assumes that you have a using directive for System.Linq at the top of your file.

此代码片段假定您在文件顶部有 System.Linq 的 using 指令。

On the other hand, if you're looking for something that can be dynamically resized, as it appears is the case for PHP (I've never actually learned it), then you may want to use a List instead of an int[]. Here's what thatcode would look like:

另一方面,如果您正在寻找可以动态调整大小的东西,就像 PHP 的情况一样(我从未真正了解过它),那么您可能想要使用 List 而不是 int[] . 下面代码的样子:

List<int> terms = Enumerable.Range(0, 400).ToList();

Note, however, that you cannot simply add a 401st element by setting terms[400] to a value. You'd instead need to call Add(), like this:

但是请注意,您不能通过将 term[400] 设置为一个值来简单地添加第 401 个元素。您需要调用 Add(),如下所示:

terms.Add(1337);

回答by jhyap

int[] terms = new int[10]; //create 10 empty index in array terms

//fill value = 400 for every index (run) in the array
//terms.Length is the total length of the array, it is equal to 10 in this case 
for (int run = 0; run < terms.Length; run++) 
{
    terms[run] = 400;
}

//print value from each of the index
for (int run = 0; run < terms.Length; run++)
{
    Console.WriteLine("Value in index {0}:\t{1}",run, terms[run]);
}

Console.ReadLine();

/*Output:

Value in index 0: 400
Value in index 1: 400
Value in index 2: 400
Value in index 3: 400
Value in index 4: 400
Value in index 5: 400
Value in index 6: 400
Value in index 7: 400
Value in index 8: 400
Value in index 9: 400
*/

/*输出:

索引 0 中的
值:400 索引 1 中的
值:400 索引 2 中的
值:400 索引 3 中的
值:400 索引 4 中的
值:400 索引 5 中的
值:400 索引 6 中的
值:400 索引 7 中的
值:400 索引 8:400
索引 9 中的值:400
*/

回答by user3404904

         static void Main(string[] args)
        {
            int[] arrayname = new int[5];/*arrayname is an array of 5 integer [5] mean in array [0],[1],[2],[3],[4],[5] because array starts with zero*/
            int i, j;


          /*initialize elements of array arrayname*/
            for (i = 0; i < 5; i++)
            {
                arrayname[i] = i + 100;
            }

             /*output each array element value*/
            for (j = 0; j < 5; j++)
            {
                Console.WriteLine("Element and output value [{0}]={1}",j,arrayname[j]);
            }
            Console.ReadKey();/*Obtains the next character or function key pressed by the user.
                                The pressed key is displayed in the console window.*/
        }