I m reading data from a source as array. a[n]
I need to add one more element to the array.
Once i get the array, i create a new array with capacity n+1 and copy all the elements to the new array and put the new element as the last element of the array.
I can do this.
Is there a better way to do this? especially with Linq?
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.Resizeworks. 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
ArrayListor, if possible, a strongly-typedList<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: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.