C# - Initialization of an array/list

Asked

Viewed 219 times

1

I wonder if you can instantiate a vector of size n and initialize it with a specific value. (Without using one for this)

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

(This doubt serves for an int[] vector, and also a int List.).

  • I think without a for will have little chance to initialize a array that big manually...

2 answers

3


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

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 the use is recurrent.

The example of this working is in .NET Fiddle

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 class Extensions us using and use the same way uses 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);
  • Thank you very much for your attention Peter Paul! But my doubt was aimed at precisely avoiding using any repeating structure to carry out this process.

  • I understood, this example was a method that would be reusable in other points of your application, but if you use Linq methods, as for example Select, Where, Any, etc, internally these methods perform the repeat structure to iterate on your items. In the end, everything would need to use iteration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.