Add multiple items to a list

3

Is there any way to add multiple Int to a list<int> at a single time?

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);
    
asked by anonymous 30.11.2015 / 19:57

3 answers

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 array of integers.

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

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

or

ContasNegativas.AddRange(new List<int> {1, 2, 3});
    
30.11.2015 / 20:13
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 });
    
30.11.2015 / 19:59
4

It would be putting in the initializer.

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

What do you need?

    
30.11.2015 / 20:00