Crear Arrays dinamico

En la busqueda constante de optimizar mi codigo, me vi en la necesidad de buscar una manera de no inicializar el tamaño del array que estoy usando. Sino ir creando su tamaño a la medida de la necesidad. Lo que hacia hasta ahora es declarar lo mas grande posible para ir cargando cuando sea necesario.Ejemplo
int [] ganadores = new int[100] para ellar los nros de cupon de un sorteo que se que no llegara a 100 premios. Pero este codigo es ineficiente ya que tiene ese riesgo de sortearse mas de 100 o de gastar memoria que no se usa. Por ello andube buscando en internet y encontre esto:
http://authors.aspalliance.com/remas/ASP.NET/VFAQNET/DynamicArrays/

Lo que necesitamos es una manera de expandir nuestro array dinamicamente.
That's where the ArrayList enters the building. You will find it in the System.Collections namespace. ArrayList can be filled with any number of elements (by means of the Add method) and provides a method that returns an array of these elements. That's exactly what we're after.

Dynamic arrays with ArrayList
public string[] GetFoo() {
System.Collections.ArrayList al = new ArrayList();
// Connect to the database and create a data reader (myReader)
while (myReader.Read()) {
// Do some cools stuff here
al.Add((string) myReader["name"]);
}
return (string[]) al.ToArray(typeof(string));
}
As you can see we're adding elements to the ArrayList object as many times as required. If the while loop iterates 3 times, we will have 3 elements. If it iterates 1003 times, we will have 1003 elements.

Les paso otro codigo donde use array list
public int[] ganadores;
System.Collections.ArrayList al = new ArrayList();
while (!encontro)
{


buscar = ValorAleatorio(this.ListView1.Items.Count);
int k = 0;
ganadores = (int[])al.ToArray(typeof(int));
while (k < ganadores.Length && !encontro)
{
if (buscar == ganadores[k])
{
encontro = true;
}
k++;
}

if (!encontro)
{
//ganadores[indice] = buscar; antes usaba asi ya declaraba int ganadores =new int[100] de cien maximo//
al.Add(buscar);
encontro = true;
}

else
{ encontro = false; }

}


Bueno Espero que les sirva
Saludos
Adalberto Montania

Comentarios