2

I have a string array, and I want to add a new value somewhere in the center, but don't know how to do this. Can anyone please make this method for me?

void AddValueToArray(String ValueToAdd, String AddAfter, ref String[] theArray) {
    // Make this Value the first value
    if(String.IsNullOrEmpty(AddAfter)) {
        theArray[0]=ValueToAdd; // WRONG: This replaces the first Val, want to Add a new String 
        return;
    }

    for(int i=0; i<theArray.Length; i++) {
        if(theArray[i]==AddAfter) {
            theArray[i++]=ValueToAdd; // WRONG: Again replaces, want to Add a new String 
            return;
        }
    }
}
Ken Kin
  • 4,503
  • 3
  • 38
  • 76
Tizz
  • 820
  • 1
  • 15
  • 31
  • 2
    Nobody here is going to do your homework... – Tomas Voracek Mar 05 '13 at 21:57
  • 2
    I am pretty sure somebody will tbh :) – bas Mar 05 '13 at 21:58
  • 2
    Hint: First you need to move all the elements of the array after the add point, increasing the array's size by one. Then set the value. Further hints: An array may not be the ideal structure for this. A `LinkedList` would probably be a lot better. Or perhaps don't store the values in order but read them in order with `OrderBy` when needed? – David Mar 05 '13 at 21:59
  • 3
    Arrays are not supposed to work like this, why do you need it to be an Array? it seems like a list its what you should use – Luis Tellez Mar 05 '13 at 22:02
  • LoL, its not homework. I just thought there would be a smarter way to do this without List = array.ToList(), list.insert(3, string), array = list.ToArray() ... – Tizz Mar 05 '13 at 22:06
  • .NET already comes with a [SortedList](http://msdn.microsoft.com/en-us/library/ms132319.aspx) class; is there some reason you can't use it? – Dour High Arch Mar 06 '13 at 00:01

3 Answers3

10

You can't add items to an array, it always remains the same size.

To get an array with the item added, you would need to allocate a new array with one more item, and copy all items from the original array to the new array.

This is certainly doable, but not efficient. You should use a List<string> instead, which already has an Insert metod.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2

This would work only in some particular case.

public static void AddValueToArray(ref String[] theArray, String valueToAdd, String addAfter) {
    var count=theArray.Length;
    Array.Resize(ref theArray, 1+count);
    var index=Array.IndexOf(theArray, addAfter);
    var array=Array.CreateInstance(typeof(String), count-index);
    Array.Copy(theArray, index, array, 0, array.Length);
    ++index;
    Array.Copy(array, 0, theArray, index, array.Length);
    theArray[index]=valueToAdd;
}

Here's a sample, but it works with Type, you might need to modify the type you need. It is an example of copying array recursively.

Community
  • 1
  • 1
Ken Kin
  • 4,503
  • 3
  • 38
  • 76
0

See how IList Insert method is implemented

kashif
  • 3,713
  • 8
  • 32
  • 47