向 C# 数组添加值

705

这可能是一个非常简单的问题 - 我刚开始学习C#,需要向数组中添加值,例如:

int[] terms;

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

如果您使用过PHP,这是我在C#中想要做的事情:

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

11
“terms[] = value;” 应该改为 “terms[] = runs;” 吗? - tymtam
在C#中,一旦创建了数组,就无法更改其大小。如果您想要类似于数组的东西,但可以添加/删除元素,请使用List<int>()。 - Kamran Bigdely
@KamranBigdely 不太准确,您可以将数组用作IList<>并使用LinQ重新分配值(using System.Linq):terms= terms.Append (21) .ToArray(); - Leandro Bardelli
1
@Leandro:每次运行时,您实际上都在创建一个新数组 --> terms = terms.Append(21).ToArray(); - Kamran Bigdely
是的,在分配时销毁,那又怎样? - Leandro Bardelli
事实上,PHP中你所熟悉的“数组”并不是计算机科学意义上的真正的数组。真正的数组是一块固定的连续的内存块。当你知道自己有一个真正的数组时,可以进行一些很好的优化,但是PHP实际上提供给你的是一个集合。现在,C#也有像List<int>这样的集合(这是你应该在这里使用的),但是当你请求一个数组时,它实际上会给你一个真正的数组。 - Joel Coehoorn
26个回答

5

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


5

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<>。数组和列表都是密集型的数据结构。


4

一种方法是通过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();
}


4

数组推送示例

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
}

4
这对我来说似乎要少麻烦得多:
var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();

3

我将添加这个变量的另一种形式。我更喜欢这种类型的功能性编码。

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

3
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
*/


你能解释一下这个解决方案吗? - Deep Frozen
Rune,我刚刚在源代码中添加了注释。希望它能回答你的问题。 - jhyap

3

如果您不知道数组的大小或已经有一个现有的数组需要添加元素。您可以通过两种方式来实现。第一种是使用通用的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>对象所需的资源会更多。

时间(以滴答为单位):

3个元素

数组调整大小时间:6

列表添加时间:16

400个元素

数组调整大小时间:305

列表添加时间:20


3
你不能直接这样做。然而,你可以使用Linq来实现:
List<int> termsLst=new List<int>();
for (int runs = 0; runs < 400; runs++)
{
    termsLst.Add(runs);
}
int[] terms = termsLst.ToArray();

如果数组terms一开始不为空,您可以首先将其转换为List,然后进行您要做的操作。例如:
    List<int> termsLst = terms.ToList();
    for (int runs = 0; runs < 400; runs++)
    {
        termsLst.Add(runs);
    }
    terms = termsLst.ToArray();

注意:不要忘记在文件开头添加using System.Linq;


2

一种不同的方法:

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

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

return scorecard.Split("!");

3
虽然稍微有些新颖,但这种方法执行了大量的字符串连接操作并进行了一次较大规模的枚举操作! 这不是最高效或易于理解/阅读的方式。 - BradleyDotNET
@Ali Humayun,你真的想使用赋值运算符“=”而不是比较运算符吗?你可以省略战斗变量并使用“runs < 400”来控制循环。 - Steve
只是练习编程的双关语。 - Ali Humayun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接