What you have described is really the only way to do it. Arrays cannot be resized in .NET, so we have to allocate a new array and copy the old into it. For example, this is how Array.Resize
works. LINQ is not really a help here, and if it was, it would just be projecting the existing array into a new one anyway - which is exactly what we've just described.
If you find you need to resize the array often, you should consider using an ArrayList
or, if possible, a strongly-typed List<T>
.
Edit:
If you are simply getting an Array from some method you cannot control, but within your code you could use an IEnumerable<T>
instead, you can use LINQ to lazy-enumerate and spare the extra array allocation:
var mySequence = originalArray.Concat(new[]{myobj});
//snip
foreach(var item in mySequence)
{
//do stuff
}
It's only when calling ToArray()
that we incur the extra overhead. Otherwise we're simply doing a single enumeration over the original array and then sneaking the extra item(s) in at the end.