向c#数组中添加值

可能是一个非常简单的一个-我开始用c#和需要添加值到一个数组,例如:

int[] terms;


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

对于那些使用过PHP的人,下面是我试图在c#中做的事情:

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

你必须先分配数组:

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[] terms = new int[400];


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


int[] terms = new int[ArraySize];




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


terms[runs] = runs;


}

这就是我的编码方式。

你不能简单地向数组中添加一个元素。您可以将元素设置在给定的位置,如fallen888所述,但我建议使用List<int>Collection<int>代替,如果需要将其转换为数组,则使用ToArray()

你可以这样做

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

# EYZ0 # EYZ1

c#数组是固定长度的,并且总是有索引。遵循Motti的解决方案:

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

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

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

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

这里提供了关于如何使用数组来做到这一点的答案。

然而,c#有一个非常方便的东西叫做System。集合

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

例如,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);
}

如果你用c# 3编写代码,你可以用一行代码来实现:

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

这段代码片段假设您有一个System的using指令。Linq在你的文件顶部。

另一方面,如果您正在寻找可以动态调整大小的东西,这似乎是PHP的情况(我实际上从未学习过它),那么您可能希望使用List而不是int[]。下面是代码的样子:

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

但是请注意,不能通过设置terms[400]来简单地添加第401个元素。相反,你需要像这样调用Add():

terms.Add(1337);
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();

/ *输出:

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

         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.*/
}
            /*arrayname is an array of 5 integer*/
int[] arrayname = new int[5];
int i, j;
/*initialize elements of array arrayname*/
for (i = 0; i < 5; i++)
{
arrayname[i] = i + 100;
}

只是不同的方法:

int runs = 0;
bool batting = true;
string scorecard;


while (batting = runs < 400)
scorecard += "!" + runs++;


return scorecard.Split("!");

如果你真的需要一个数组,下面可能是最简单的:

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<T>: 要做到这一点,你需要将数组转换为var termsList = terms.ToList();并使用Add方法。完成后使用var terms = termsList.ToArray();方法转换回数组

var terms = default(int[]);
var termsList = terms == null ? new List<int>() : terms.ToList();


for(var i = 0; i < 400; i++)
termsList.Add(i);


terms = termsList.ToArray();

第二种方法是调整当前数组的大小:

var terms = default(int[]);


for(var i = 0; i < 400; i++)
{
if(terms == null)
terms = new int[1];
else
Array.Resize<int>(ref terms, terms.Length + 1);
    

terms[terms.Length - 1] = i;
}

如果你使用的是。net 3.5 Array.Add(...);

这两种方法都允许您动态地进行操作。如果你要添加很多项目,那么就使用List<T>。如果只有几个项,那么调整数组的大小会有更好的性能。这是因为您在创建List<T>对象时受到了更多的影响。

# EYZ0 # EYZ1

3项

数组调整大小时间:6

List添加时间:16

400件

数组大小调整时间:305

List添加时间:20

正如其他人所描述的那样,使用List作为中介是最简单的方法,但由于您的输入是一个数组,并且您不希望将数据保存在List中,因此我假定您可能关心性能。

最有效的方法可能是分配一个新数组,然后使用array。Copy或Array.CopyTo。如果你只是想在列表的末尾添加一个项目,这并不难:

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

如果需要,我还可以发布以目标索引作为输入的Insert扩展方法的代码。它稍微复杂一点,使用静态方法Array。复制1-2次。

根据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;
}

这允许向数组中添加多个项,或者只是将一个数组作为参数来连接两个数组。

使用Linq的方法Concat可以简化这个过程

int[] array = new int[] { 3, 4 };


array = array.Concat(new int[] { 2 }).ToArray();
< p >结果 3、4、2 < / p >

我将为另一个变体添加这个。我更喜欢这种类型的函数编码行。

Enumerable.Range(0, 400).Select(x => x).ToArray();

使用c#将列表值添加到字符串数组中,而不使用ToArray()方法

        List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
list.Add("four");
list.Add("five");
string[] values = new string[list.Count];//assigning the count for array
for(int i=0;i<list.Count;i++)
{
values[i] = list[i].ToString();
}

值数组的输出包含:

一个

两个

三个

四个

五个

一种方法是通过LINQ填充数组

如果你想用一个元素填充一个数组 你可以简单地写

string[] arrayToBeFilled;
arrayToBeFilled= arrayToBeFilled.Append("str").ToArray();

此外,如果你想用多个元素填充一个数组,你可以使用

.循环中的先前代码
//the array you want to fill values in
string[] arrayToBeFilled;
//list of values that you want to fill inside an array
List<string> listToFill = new List<string> { "a1", "a2", "a3" };
//looping through list to start filling the array


foreach (string str in listToFill){
// here are the LINQ extensions
arrayToBeFilled= arrayToBeFilled.Append(str).ToArray();
}


你不能直接这么做。然而,你可以使用Linq来做到这一点:

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

如果数组条款在开始时不是空的,你可以先将它转换为列表,然后再做你的事情。如:

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

不要错过在文件开头添加“使用来;”。

这对我来说似乎不那么麻烦:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();

你可以用一个列表。以下是如何

List<string> info = new List<string>();
info.Add("finally worked");

如果你需要返回这个数组

return info.ToArray();

到2019年,你可以在一行中使用AppendPrependLinQ

using System.Linq;

然后在NET 6.0中:

terms = terms.Append(21);

或低于NET 6.0的版本

terms = terms.Append(21).ToArray();

数组推送示例 . rref ="https://dotnetfiddle.net/dTnU2t" rel="nofollow noreferrer">

public void ArrayPush<T>(ref T[] table, object value)
{
Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
table.SetValue(value, table.Length - 1); // Setting the value for the new element
}

下面是如何处理向数组中添加新数字和字符串的一种方法:

int[] ids = new int[10];
ids[0] = 1;
string[] names = new string[10];


do
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Enter Name");
names[i] = Convert.ToString(Console.ReadLine());
Console.WriteLine($"The Name is: {names[i]}");
Console.WriteLine($"the index of name is: {i}");
Console.WriteLine("Enter ID");
ids[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"The number is: {ids[i]}");
Console.WriteLine($"the index is: {i}");
}




} while (names.Length <= 10);