簡體   English   中英

將值添加到 C# 數組

[英]Adding values to a C# array

這可能是一個非常簡單的 - 我從 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();

編輯: a) List<T> 上的for循環比 List<T> 上的foreach循環便宜 2 倍多,b) 數組循環比 List<T> 上循環便宜約 2 倍,c) 循環使用for 的數組比使用foreach (我們大多數人都這樣做)在 List<T> 上循環便宜 5 倍。

使用Linq的方法Concat使這變得簡單

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

array = array.Concat(new int[] { 2 }).ToArray();

結果 3,4,2

如果您使用 C# 3 編寫,則可以使用單行代碼:

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

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

另一方面,如果您正在尋找可以動態調整大小的東西,就像 PHP 的情況一樣(我從未真正了解過它),那么您可能想要使用 List 而不是 int[] . 下面代碼的樣子:

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

但是請注意,您不能通過將 term[400] 設置為一個值來簡單地添加第 401 個元素。 您需要調用 Add(),如下所示:

terms.Add(1337);

此處提供了有關如何使用數組執行此操作的答案。

然而,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);
}

正如其他人所描述的那樣,使用 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.Copy 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;
    }

這允許向數組添加多個項目,或者僅將數組作為參數傳遞以連接兩個數組。

到 2019 年,您可以在一行中使用AppendPrepend使用LinQ

using System.Linq;

然后:

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

您必須先分配數組:

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;

}

那將是我編碼的方式。

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<>。 數組和列表都是密集的。

如果你真的需要一個數組,以下可能是最簡單的:

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

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

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

您不能簡單地將元素添加到數組中。 您可以在給定位置設置元素,如fall888概述,但我建議使用List<int>Collection<int>代替,如果需要將其轉換為數組,請使用ToArray()

我將為另一個變體添加這個。 我更喜歡這種類型的功能編碼行。

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

只是一種不同的方法:

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

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

return scorecard.Split("!");

如果您不知道數組的大小或已經有要添加到的現有數組。 您可以通過兩種方式解決此問題。 第一種是使用通用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

你不能直接這樣做。 但是,您可以使用Linq來執行此操作:

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

如果數組項一開始不是空的,您可以先將其轉換為List,然后再做您的 stuf。 像:

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

注意:不要錯過使用 System.Linq添加 ' ; ' 在文件的開頭。

這對我來說似乎少了很多麻煩:

var usageList = usageArray.ToList();
usageList.Add("newstuff");
usageArray = usageList.ToArray();
int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}
         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;
            }

使用 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();
        }

值數組的輸出包含:

兩個

你可以用一個列表來做到這一點。 這是如何

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

如果你需要返回這個數組做

return info.ToArray();

數組推送示例

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
}

這是處理向 Array 添加新數字和字符串的一種方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM