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 :)
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();
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();
I recommend the answer found here: How do I concatenate two arrays in C#?
e.g.
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
The solution looks like great fun, but it is possible to concatenate arrays in just two statements. When you're handling large byte arrays, I suppose it is inefficient to use a Linked List to contain each byte.
Here is a code sample for reading bytes from a stream and extending a byte array on the fly:
byte[] buf = new byte[8192]; byte[] result = new byte[0]; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { Array.Resize(ref result, result.Length + count); Array.Copy(buf, 0, result, result.Length - count, count); } } while (count > 0); // any more data to read? resStream.Close();