ASP.NET - How to merge (concatenate) two or more arrays in C# A simple yet useful one-liner that you can use to concatenate two or more arrays using C# and LINQ in ASP.NET 4, ASP.NET MVC and ASP.NET Core

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.


About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.