Count the number of elements of an array in C #

3

I will have an array like the following:

string[] arr1 = { "one", "two", "three" };

How could I do to count the total number of elements in my array. Try adding Count but it returns me:

El nombre 'arr1.Count' no existe en el contexto actual.

If there is no such method, is there any simple way or even using loops to count the number of elements of an array in C #?

    
asked by jeronimo urtado 22.03.2017 в 15:50
source

3 answers

7

Use Length :

  

arr1.Length

Example:

string[] arr1 = { "one", "two", "three" };
Console.WriteLine("Cantidad de elementos en el arreglo: " + arr1.Length);
// Resultado: Cantidad de elementos en el arreglo: 3
    
answered by 22.03.2017 / 15:53
source
4

Expanding your needs, if you have an array of a dimension with

array.GetLength(0)

you retrieve the length of this unique and first dimension, if you have two dimensions with

array.GetLength(1) 

you recover the length of the second dimension ... and so with all the dimensions you can have.

    
answered by 22.03.2017 в 16:00
1

Arrays do not have a Count property. You have to use the Count :

arr1.Count();

Or as the friend Mauricio Arias says, use the property Length . In fact, I would recommend you use this last one and accept your answer.

    
answered by 22.03.2017 в 15:51