C # massive insertion into data structures

In C # you can do the following:

List<int> registers = new List<int> { 1, 2, 3, 4 };

This will create a list with 1, 2, 3 and 4 in the list. Suppose I was given a list from some function, and I want to insert a bunch of numbers, as shown below:

List<int> register = somewhere();
register.Add(1);
register.Add(2);
register.Add(3);
register.Add(4);

Is there a cleaner way to do this, as the snippet above?

+3
source share
3 answers

Assuming that the new elements are already in some enumerable form, the method AddRange()allows you to add them all at a time

var toBeAdded = new int[] { 1,2,3,4 };
register.AddRange(toBeAdded);
+4
source

Do you mean something like this?

List<int> register = somewhere();
register.AddRange(new List<int> { 1, 2, 3, 4 });
+2
source

I think the cleanest thing you can get is:

List<int> register = somewhere();
register.AddRange(new[] { 1, 2, 3, 4 });

However, it is not always possible to implicitly enter an array.

0
source

Source: https://habr.com/ru/post/1743118/


All Articles