Most efficient way to append arrays in C#? Most efficient way to append arrays in C#? arrays arrays

Most efficient way to append arrays in C#?


You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T> which can grow as it needs to.

Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.

See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)


I believe if you have 2 arrays of the same type that you want to combine into a third array, there's a very simple way to do that.

here's the code:

String[] theHTMLFiles = Directory.GetFiles(basePath, "*.html");String[] thexmlFiles = Directory.GetFiles(basePath, "*.xml");List<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));String[] finalArray = finalList.ToArray();


Concatenating arrays is simple using linq extensions which come standard with .Net 4

Biggest thing to remember is that linq works with IEnumerable<T> objects, so in order to get an array back as your result then you must use the .ToArray() method at the end

Example of concatenating two byte arrays:

byte[] firstArray = {2,45,79,33};byte[] secondArray = {55,4,7,81};byte[] result = firstArray.Concat(secondArray).ToArray();