简体   繁体   English

将值添加到 C# 数组

[英]Adding values to a C# array

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

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) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 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 倍。

Using Linq 's method Concat makes this simple使用Linq的方法Concat使这变得简单

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

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

result 3,4,2结果 3,4,2

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[].另一方面,如果您正在寻找可以动态调整大小的东西,就像 PHP 的情况一样(我从未真正了解过它),那么您可能想要使用 List 而不是 int[] . Here's what that code would look like:下面代码的样子:

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.但是请注意,您不能通过将 term[400] 设置为一个值来简单地添加第 401 个元素。 You'd instead need to call Add(), like this:您需要调用 Add(),如下所示:

terms.Add(1337);

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

Using a List as an intermediary is the easiest way, as others have described, but since your input is an array and you don't just want to keep the data in a List, I presume you might be concerned about performance.正如其他人所描述的那样,使用 List 作为中介是最简单的方法,但是由于您的输入是一个数组并且您不只是想将数据保存在 List 中,我认为您可能会担心性能。

The most efficient method is likely allocating a new array and then using Array.Copy or Array.CopyTo.最有效的方法可能是分配一个新数组,然后使用 Array.Copy 或 Array.CopyTo。 This is not hard if you just want to add an item to the end of the list:如果您只想在列表末尾添加一个项目,这并不难:

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

I can also post code for an Insert extension method that takes a destination index as input, if desired.如果需要,我还可以发布将目标索引作为输入的 Insert 扩展方法的代码。 It's a little more complicated and uses the static method Array.Copy 1-2 times.它有点复杂,使用静态方法 Array.Copy 1-2 次。

Based on the answer of Thracx (I don't have enough points to answer):基于 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;
    }

This allows to add more than just one item to the array, or just pass an array as a parameter to join two arrays.这允许向数组添加多个项目,或者仅将数组作为参数传递以连接两个数组。

By 2019 you can use Append , Prepend using LinQ in just one line到 2019 年,您可以在一行中使用AppendPrepend使用LinQ

using System.Linq;

and then:然后:

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

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;
}
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.那将是我编码的方式。

C# arrays are fixed length and always indexed. C# 数组是固定长度的,并且总是索引的。 Go with Motti's solution:使用 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.请注意,此数组是一个密集数组,是一个 400 字节的连续块,您可以在其中放置内容。 If you want a dynamically sized array, use a List<int>.如果您想要一个动态大小的数组,请使用 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#. int[] 和 List<int> 都不是关联数组——这将是 C# 中的 Dictionary<>。 Both arrays and lists are dense.数组和列表都是密集的。

If you really need an array the following is probly the simplest:如果你真的需要一个数组,以下可能是最简单的:

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

one approach is to fill an array via LINQ一种方法是通过 LINQ 填充数组

if you want to fill an array with one element you can simply write如果你想用一个元素填充一个数组,你可以简单地写

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

furthermore, If you want to fill an array with multiple elements you can use the previous code in a loop此外,如果你想用多个元素填充数组,你可以在循环中使用前面的代码

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

/*Output: /*输出:

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

You can't just add an element to an array easily.您不能简单地将元素添加到数组中。 You can set the element at a given position as fallen888 outlined, 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概述,但我建议使用List<int>Collection<int>代替,如果需要将其转换为数组,请使用ToArray()

I will add this for a another variant.我将为另一个变体添加这个。 I prefer this type of functional coding lines more.我更喜欢这种类型的功能编码行。

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

Just a different approach:只是一种不同的方法:

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

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

return scorecard.Split("!");

If you don't know the size of the Array or already have an existing array that you are adding to.如果您不知道数组的大小或已经有要添加到的现有数组。 You can go about this in two ways.您可以通过两种方式解决此问题。 The first is using a generic List<T> : To do this you will want convert the array to a var termsList = terms.ToList();第一种是使用通用List<T> :为此,您需要将数组转换为var termsList = terms.ToList(); and use the Add method.并使用 Add 方法。 Then when done use the var terms = termsList.ToArray();然后完成后使用var terms = termsList.ToArray(); method to convert back to an array.转换回数组的方法。

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

The second way is resizing the current array:第二种方法是调整当前数组的大小:

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

If you are using .NET 3.5 Array.Add(...);如果您使用 .NET 3.5 Array.Add(...);

Both of these will allow you to do it dynamically.这两种方法都可以让你动态地做到这一点。 If you will be adding lots of items then just use a List<T> .如果您将添加大量项目,则只需使用List<T> If it's just a couple of items then it will have better performance resizing the array.如果它只是几个项目,那么调整数组大小会有更好的性能。 This is because you take more of a hit for creating the List<T> object.这是因为您在创建List<T>对象时需要付出更多努力。

Times in ticks:时报蜱:

3 items 3 项

Array Resize Time: 6阵列大小调整时间:6

List Add Time: 16列表添加时间:16

400 items 400 项

Array Resize Time: 305阵列调整大小时间:305

List Add Time: 20列表添加时间:20

You can't do this directly.你不能直接这样做。 However, you can use Linq to do this:但是,您可以使用Linq来执行此操作:

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

If the array terms wasn't empty in the beginning, you can convert it to List first then do your stuf.如果数组项一开始不是空的,您可以先将其转换为List,然后再做您的 stuf。 Like:像:

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

Note: don't miss adding ' using System.Linq;注意:不要错过使用 System.Linq添加 ' ; ' at the begaining of the file. ' 在文件的开头。

This seems like a lot less trouble to me:这对我来说似乎少了很多麻烦:

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

To add the list values to string array using C# without using ToArray() method使用 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();
        }

Output of the value array contains:值数组的输出包含:

one

two两个

three

four

five

You can do this is with a list.你可以用一个列表来做到这一点。 here is how这是如何

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

and if you need to return this array do如果你需要返回这个数组做

return info.ToArray();

Array Push Example数组推送示例

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
}

Here is one way how to deal with adding new numbers and strings to Array:这是处理向 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