Created
April 6, 2017 21:22
-
-
Save Reflej0/bd42731fa9c29e89d6602ce8c119a704 to your computer and use it in GitHub Desktop.
Colecciones en C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
* | |
* Para cambiar esta plantilla use Herramientas | Opciones | Codificación | Editar Encabezados Estándar | |
*/ | |
using System; | |
// Necesario para ArrayList. | |
using System.Collections; | |
// Necesario para List. | |
using System.Collections.Generic; | |
namespace ac_test | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
// Colección normal. Almacena elementos de tipo "object" | |
ArrayList c = new ArrayList(); | |
// Colección genérica. Almacena elementos de tipo especificado solamente. | |
List<int> cg = new List<int>(); | |
int a = cg[0]; | |
// Agregar elementos en la colección. | |
c.Add(4); | |
c.Add(5); | |
int suma = 0; | |
// La propiedad Count informa el número de elementos de la colección. | |
for (int i = 0; i < c.Count; i++) { | |
// Accedo a los elementos a través de un índice. El índice comienza en 0. | |
// Al ser una colección normal guarda los elementos como "object" por lo tanto | |
// para trabajar con un elemento necesito convertir al tipo de dato correcto. | |
suma += (int) c[i]; | |
} | |
// Remueve un elemento por su posición en la colección. | |
c.RemoveAt(0); | |
// Otra forma de recorrer una colección. | |
foreach (int e in c) { | |
Console.WriteLine(e); | |
} | |
// Remueve un elemento mediante un criterio de igualdad (método Equals) | |
c.Remove(7); | |
// Elimina todos los elementos que contiene una colección. | |
c.Clear(); | |
Console.ReadKey(true); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment