Add multiple items to a list

Asked

Viewed 2,350 times

3

Is there any way to add several Intin a list<int>all at once?

Type

List<Int32> ContasNegativas = new List<Int32>();

ContasNegativas.AddRange(30301, 30302, 30303, 30304, 30305, 30306, 30341, 30342, 30343, 30344, 30345, 30346, 30401,30403, 30421, 30423, 40101, 40102, 40111, 40112, 40121, 40122, 40123, 50101, 50102, 50103, 50104, 50105, 50231);

3 answers

6

You can add them as an enumerable (for example, an array):

List<Int32> ContasNegativas = new List<Int32>();
ContasNegativas.AddRange(new int[] { 30301, 30302, 30303, 30304, 30305, 30306, 30341, 30342, 30343, 30344, 30345, 30346, 30401,30403, 30421, 30423, 40101, 40102, 40111, 40112, 40121, 40122, 40123, 50101, 50102, 50103, 50104, 50105, 50231 });

4

Would be putting in the initializer.

var lista = new List<int>() {1, 2, 3, 4};

What you need?

4


Your reasoning is almost right, the only difference is that the method AddRange() gets a IEnumerable<T> instead of several T's.

The use would be:

ContasNegativas.AddRange(new [] {30301, 30302, 30303, 30304});

Note: C# is smart enough to understand that new [] {int, ...} refers to a new integer array.

You can also pass a List as a parameter (because the class List also implements IEnumerable).

var novaLista = new List<int> {1, 2, 3};
ContasNegativas.AddRange(novaLista);

or

ContasNegativas.AddRange(new List<int> {1, 2, 3});
  • 1

    Perfect guy vlw...

Browser other questions tagged

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