C # - Starting an array / list

1

I would like to know if you can instantiate a vector of size n and already initialize it with a specific value. (Without using a for for this)

For example, I would instantiate a vector, which will have size 100 and all indexes with -1.

(This question is for a vector of int [], and also an int List.)

    
asked by anonymous 13.08.2018 / 14:59

2 answers

3

You can use a workaround to create this array with the following statement:

Enumerable.Range(0, 100).Select((y) => -1).ToArray();

Note that there is an overhead to do this, but it solves what you want, you can create a factory method if it is recurring.

The example of this working is in .NET Fiddle

    
13.08.2018 / 15:16
1

You can create an extension method to popular your collections. Create a static class with a static method to become an extension method:

public static class Extensions
{
    /// <summary>
    /// Método para popular a coleção de dados
    /// </summary>
    /// <typeparam name="TypeValue">Tipo de dados do valor que vai ser preenchido</typeparam>
    /// <param name="collection">Coleção de dados que será preenchida</param>
    /// <param name="value">Valor que vai ser inserido</param>
    /// <param name="indexSize">Quantos itens da coleção serão preenchidos</param>
    public static void PopularColecao<TypeValue>(this IList collection, TypeValue value, int indexSize)
    {
        if (collection.IsFixedSize)
        {
            for (int i = 0; i < indexSize; i++)
                collection[i] = value;
        }
        else
        {
            for (int i = 0; i < indexSize; i++)
                collection.Add(value);
        }
    }
}

To use the extension method, add the namespace of your Extensions class to using and use the same way use the Linq functions:

 List<int> lista = new List<int>();
 ArrayList arrayList = new ArrayList();
 int[] array = new int[10];

 //A lista será populada com o valor 5 para 10 posições
 lista.PopularColecao(5, 10);

 //O array list será populado com o valor 10 para 10 posições
 arrayList.PopularColecao(10, 10);

 //O array será populado com o valor 8 para 2 posições
 array.PopularColecao(8, 2);
    
13.08.2018 / 15:29