这可能是一个非常简单的问题 - 我刚开始学习C#,需要向数组中添加值,例如:
int[] terms;
for(int runs = 0; runs < 400; runs++)
{
terms[] = runs;
}
如果您使用过PHP,这是我在C#中想要做的事情:
$arr = array();
for ($i = 0; $i < 10; $i++) {
$arr[] = $i;
}
您可以这样做 -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
或者,您可以使用列表-使用列表的优点是,在实例化列表时不需要知道数组大小。
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();
如果你正在使用 C# 3,你可以用一行代码来实现:
int[] terms = Enumerable.Range(0, 400).ToArray();
List<int> terms = Enumerable.Range(0, 400).ToList();
terms.Add(1337);
截至2019年,您可以使用Linq
中的Append
和Prepend
仅用一行代码。
using System.Linq;
然后在NET 6.0中:
terms = terms.Append(21);
或者版本低于.NET 6.0
terms = terms.Append(21).ToArray();
这里提供了使用数组执行它的答案。但是,C# 有一个非常方便的东西叫做 System.Collections。
集合是使用数组的花哨替代品,尽管其中许多集合在内部使用数组。
例如,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);
}
public static T[] Add<T>(this T[] target, T item)
{
if (target == null)
{
//TODO: Return null or throw ArgumentNullException;
}
T[] result = new T[target.Length + 1];
target.CopyTo(result, 0);
result[target.Length] = item;
return result;
}
如果需要,我还可以发布一种插入扩展方法的代码,该方法将目标索引作为输入。它稍微复杂一些,使用静态方法Array.Copy 1-2次。
T[] result = new T[target.Length + 1]; target.CopyTo(result, 0);
,而不直接使用Array.Resize呢? - EyesShriveledToRaisins基于Thracx的回答(我没有足够的积分来回答):
public static T[] Add<T>(this T[] target, params T[] items)
{
// Validate the parameters
if (target == null) {
target = new T[] { };
}
if (items== null) {
items = new T[] { };
}
// Join the arrays
T[] result = new T[target.Length + items.Length];
target.CopyTo(result, 0);
items.CopyTo(result, target.Length);
return result;
}
首先需要分配数组:
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;
}
int ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
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);
}
int [] terms = list.ToArray();
List<int>
这样的集合(这是你应该在这里使用的),但是当你请求一个数组时,它实际上会给你一个真正的数组。 - Joel Coehoorn