Agregar valores a una matriz de C #


Probablemente uno muy simple esto - estoy empezando con C# y necesito agregar valores a una matriz, por ejemplo:

int[] terms;

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

Para aquellos que han usado PHP, esto es lo que estoy tratando de hacer en C#:

$arr = array();
for ($i = 0; $i < 10; $i++) {
    $arr[] = $i;
}
 391
Author: AustinWBryan, 2008-10-15

17 answers

Puedes hacerlo de esta manera -

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

Alternativamente, puede usar Listas - la ventaja con las listas es que no necesita saber el tamaño de la matriz al instanciar la lista.

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

Editar: a) para los bucles en la Lista son un poco más de 2 veces más baratos que foreach los bucles en la Lista, b) El bucle en la matriz es alrededor de 2 veces más barato que el bucle en la Lista, c) el bucle en la matriz usando para {[8] } es 5 veces más barato que el bucle foreach (que la mayoría de nosotros hacemos).

 664
Author: Tamas Czinege,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:38

Si estás escribiendo en C # 3, puedes hacerlo con una sola línea:

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

Este fragmento de código asume que tiene una directiva using para System.Linq en la parte superior de su archivo.

Por otro lado, si estás buscando algo que se pueda cambiar de tamaño dinámicamente, como parece ser el caso de PHP (nunca lo he aprendido), entonces es posible que desees usar una Lista en lugar de un int[]. Así es como se vería ese código:

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

Tenga en cuenta, sin embargo, que usted no puede simplemente agregue un elemento 401st estableciendo términos [400] a un valor. En su lugar, necesitas llamar a Add (), así:

terms.Add(1337);
 75
Author: David Mitchell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-29 00:52:30

Las respuestas sobre cómo hacerlo usando una matriz se proporcionan aquí.

Sin embargo, C# tiene una cosa muy útil llamada Sistema.Colecciones :)

Las colecciones son alternativas sofisticadas al uso de una matriz, aunque muchas de ellas usan una matriz internamente.

Por ejemplo, C# tiene una colección llamada List que funciona muy similar a la matriz 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);
}
 33
Author: FlySwat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-14 21:11:07

Usando el método de Linq Concat {[3] } hace esto simple

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

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

Resultado 3,4,2

 29
Author: Yitzhak Weinberg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-08 17:47:09

Primero tienes que asignar el array:

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;
}
 8
Author: Motti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-04 07:28:13

Usar una Lista como intermediario es la forma más fácil, como otros han descrito, pero como su entrada es una matriz y no solo desea mantener los datos en una Lista, supongo que podría estar preocupado por el rendimiento.

El método más eficiente es probablemente asignar un nuevo array y luego usar Array.Copia o Matriz.Copiado. Esto no es difícil si solo desea agregar un elemento al final de la lista:

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

También puedo enviar código para un método de extensión Insert que toma un índice de destino como entrada, si se desea. Es un poco más complicado y utiliza el método estático Array.Copia 1-2 veces.

 8
Author: Thracx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-23 06:05:03

Basado en la respuesta de Thracx (no tengo suficientes puntos para responder):

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

Esto permite añadir más de un elemento a la matriz, o simplemente pasar una matriz como parámetro para unir dos matrices.

 7
Author: Mark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 03:51:39
int ArraySize = 400;

int[] terms = new int[ArraySize];


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

    terms[runs] = runs;

}

Así sería como lo codificaría.

 5
Author: JB King,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-14 21:08:12

Los arrays de C# son de longitud fija y siempre están indexados. Ir con la solución de Motti:

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

Tenga en cuenta que esta matriz es una matriz densa, un bloque contiguo de 400 bytes donde puede soltar cosas. Si desea una matriz de tamaño dinámico, utilice una lista.

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

Ni int [] ni List es un array asociativo that que sería un Diccionario en C#. Tanto los arrays como las listas son densos.

 3
Author: Jimmy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-30 13:48:22
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();

/ * Salida:

Valor en el índice 0: 400
Valor en el índice 1: 400
Valor en el índice 2: 400
Valor en el índice 3: 400
Valor en el índice 4: 400
Valor en el índice 5: 400
Valor en el índice 6: 400
Valor en el índice 7: 400
Valor en el índice 8: 400
Valor en el índice 9: 400
*/

 2
Author: jhyap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-08 07:32:42

No puede simplemente agregar un elemento a un array fácilmente. Puede establecer el elemento en una posición dada como fallen888 delineado, pero recomiendo usar un List<int> o un Collection<int> en su lugar, y usar ToArray() si necesita convertirlo en un array.

 2
Author: Michael Stum,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-15 16:41:37

Si realmente necesita un array, lo siguiente es probablemente el más simple:

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();
 1
Author: Steve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-10 03:18:38

Si no conoce el tamaño de la matriz o ya tiene una matriz existente a la que está agregando. Puedes hacer esto de dos maneras. El primero es usar un {[2 genérico]}: Para hacer esto, querrá convertir la matriz a var termsList = terms.ToList(); y usar el método Add. Luego, cuando termine, use el método var terms = termsList.ToArray(); para convertir de nuevo a una matriz.

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

La segunda forma es redimensionar el array actual:

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

Si está utilizando. NET 3.5 Array.Add(...);

Ambos te permitirán hacerlo dinámicamente. Si va a agregar muchos elementos, simplemente use un List<T>. Si es solo un par de elementos, entonces tendrá un mejor rendimiento redimensionando la matriz. Esto se debe a que toma más de un golpe para crear el objeto List<T>.

Tiempos en garrapatas:

3 temas

Tiempo de redimensionamiento del Array: 6

Lista Añadir Tiempo: 16

400 temas

Tiempo de redimensionamiento del Array: 305

Lista Añadir tiempo: 20

 1
Author: LCarter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-18 23:13:50

Solo un enfoque diferente:

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

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

return scorecard.Split("!");
 1
Author: Ali Humayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-17 13:26:12
int[] terms = new int[400];

for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}
 0
Author: Johnno Nolan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-14 21:07:06
         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.*/
        }
 0
Author: user3404904,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 10:38:23
            /*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;
            }
 0
Author: user3404904,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-13 10:44:56