Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# massive insertion into data structures

Tags:

c#

In C#, you can do the following:

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

This will produce a list with 1, 2, 3, and 4 in the list. Suppose that I am given a list from some function and I want to insert a bunch of numbers like the following:

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

Is there a cleaner way of doing this like the snippet above?

like image 498
Seabass Avatar asked Jun 14 '26 04:06

Seabass


2 Answers

Assuming the new items are in some kind of enumerable form already, the AddRange() method allows you to add them all in one go:

var toBeAdded = new int[] { 1,2,3,4 };
register.AddRange(toBeAdded);
like image 95
Jørn Schou-Rode Avatar answered Jun 16 '26 18:06

Jørn Schou-Rode


You mean something like this?

List<int> register = somewhere();
register.AddRange(new List<int> { 1, 2, 3, 4 });
like image 23
Oded Avatar answered Jun 16 '26 19:06

Oded



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!