Site icon Ryadel

ASP.NET - How to merge (concatenate) two or more arrays in C#

How to handle multipage TIFF files with ASP.NET C# (GDI+ alternative)

If you've stumbled upon this post, it probably means that you're looking for a way to solve this simple task:

There are a number of methods that can be used, such as:

  • Instantiate a  List<int>  , use the AddRange  method to add the arrays one at a time, and then use ToArray()  to transform  it into an array;
  • Instantiate an int[] with a size equal to the sum of a.Length , b.Length  and c.Length  and then use the CopyTo() method to copy the array contents there.

... And so on.

Well, this is the one-liner I've came up with:

The good thing about the Concat()  method is that we can use it at initialization level, for example to define a static concatenation of static arrays:

This cannot be done using the other workarounds.

However, doing this has two caveats that you need to consider:

  • The Concat method creates an iterator over both arrays: it does not create a new array, thus being efficient in terms of memory used: however, the subsequent ToArray will negate such advantage, since it will actually create a new array and take up the memory for the new array.
  • As this StackOverflow thread clearly explains, Concat will be rather inefficient for large arrays: it should only be used for medium-sized arrays (up to 10000 elements each).
What if we need to concat huge-sized arrays?
Here's a decent answer (performance-wise):
Or (if you are a fan of one-liners):
Although the latter method is much more elegant, the former one is definitely better for performance.

Keep in mind that you can gain even bigger performance advantage by using Buffer.BlockCopy over Array.CopyTo, as explained here: however, you won't gain much, and I tend to favor the Array.CopyTo method as it's much more readable when dealing with arrays.

 

Exit mobile version