Adding an element to an array

22,604

Solution 1

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.

Solution 2

C# yield (no extra storage needed)

Using C# yield allows you to return your array and more without ever allocating extra storage. After yielding each element of the original array you can slip in any extra elements easily like so:

IEnumerable<int> GetEverything() {

    // first return the entire original array
    foreach(int num in arrNumbers)
        yield return num;

    // then slip in extra element at the end
    yield return 5;   // yield even more elements if you want...
}

and then you can use it like so:

foreach (int n in GetEverything())
    Console.WriteLine(n);

There's no real need to pull out LINQ in this situation because the yield statement is simple and EXACTLY suited to your need.

Solution 3

If you want to put to arrays together using LINQ, you can use Concat:

var combined = array1.Concat(new[] { element }).ToArray();

However, you are now creating a number of different arrays for your collection. A better choice would be to just use a List. It will be backed by a single array and expanded automatically for you.

Solution 4

You can use Array.Resize for this: http://msdn.microsoft.com/en-us/library/bb348051.aspx

It basically does what you've done manually but is a bit neater.

If you are adding more than one element to the array on a regular basis I'd recommend moving to a list though as it's going to be more efficient for insertions.

Solution 5

You could just use the array to initialize a list.

var stuff = new List<object>( a );
stuff.Add( moreStuff );
Share:
22,604

Related videos on Youtube

DarthVader
Author by

DarthVader

Updated on September 12, 2020

Comments

  • DarthVader
    DarthVader over 3 years

    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?

  • DarthVader
    DarthVader almost 14 years
    unfortunately, the data source returns array, i cant help it.
  • JonDrnek
    JonDrnek almost 14 years
    This is slightly worse than simply copying the old array directly into the new one.
  • Jerod Houghtelling
    Jerod Houghtelling almost 14 years
    I agree it's not the most efficient way to probably handle this. I like your use of the Concat method. I overlooked that one. I have up voted your answer.
  • Admin
    Admin almost 14 years
    Have you actually tested that extension method? Because if it works, it means the this argument gets passed by reference, which would surprise me.
  • Jerod Houghtelling
    Jerod Houghtelling almost 14 years
    @Isaac, unfortunately I didn't test that routine, it was an afterthought.
  • Jerod Houghtelling
    Jerod Houghtelling almost 14 years
    I updated the code example to let somebody know that it might not work. I decided to leave it because I think an extension method for this may still be a good solution.
  • Admin
    Admin almost 14 years
    I think it'll compile; it just won't have any effect.
  • Kirk Broadhurst
    Kirk Broadhurst almost 14 years
    @user what is stopping your from changing the datasource to a List once you receive it? Why keep it as an inflexible array?
  • DarthVader
    DarthVader almost 14 years
    because i have to store it back as an array. so changing that to a list and then back to an array is an overkill isnt it?
  • onmyway133
    onmyway133 about 11 years
    @RexM so Add() method works the same way (create new array) ?
  • JonDrnek
    JonDrnek about 11 years
    @entropy what Add method are you referring to?
  • onmyway133
    onmyway133 about 11 years
    @RexM Add method of List<T>
  • JonDrnek
    JonDrnek about 11 years
    @entropy this question is about resizing arrays. List<T> is not like an array.