Cippo
Cippo

Reputation: 1011

Adding elements to a C# array

I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.

Upvotes: 11

Views: 189695

Answers (10)

qwlice
qwlice

Reputation: 596

One liner:

    string[] items = new string[] { "a", "b" };

    // this adds "c" to the string array:
    items = new List<string>(items) { "c" }.ToArray();      

Upvotes: 3

Kirill Shur
Kirill Shur

Reputation: 290

You can use this snippet:

static void Main(string[] args)
{



        Console.WriteLine("Enter number:");
        int fnum = 0;
        bool chek = Int32.TryParse(Console.ReadLine(),out fnum);            


        Console.WriteLine("Enter number:");
        int snum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out snum);


        Console.WriteLine("Enter number:");
        int thnum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out thnum);


        int[] arr = AddToArr(fnum,snum,thnum);

        IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
        {  
            return s;
        });


        Console.WriteLine("Here your result:");


        oarr.ToList().FindAll(delegate(int num) {

            Console.WriteLine(num);

            return num > 0;

        });



}



public static int[] AddToArr(params int[] arr) {

    return arr;
}

I hope this will help to you, just change the type

Upvotes: 0

Prophet Lamb
Prophet Lamb

Reputation: 610

What's abaut this one:

List<int> tmpList = intArry.ToList(); tmpList.Add(anyInt); intArry = tmpList.ToArray();

Upvotes: 1

musefan
musefan

Reputation: 48415

The obvious suggestion would be to use a List<string> instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.

Of course, I want to make things more interesting (my day that is), so I will answer your question directly.

Here are a couple of functions that will Add and Remove elements from a string[]...

string[] Add(string[] array, string newValue){
    int newLength = array.Length + 1;

    string[] result = new string[newLength];

    for(int i = 0; i < array.Length; i++)
        result[i] = array[i];

    result[newLength -1] = newValue;

    return result;
}

string[] RemoveAt(string[] array, int index){
    int newLength = array.Length - 1;

    if(newLength < 1)
    {
        return array;//probably want to do some better logic for removing the last element
    }

    //this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way

    string[] result = new string[newLength];
    int newCounter = 0;
    for(int i = 0; i < array.Length; i++)
    {
        if(i == index)//it is assumed at this point i will match index once only
        {
            continue;
        }
        result[newCounter] = array[i];
        newCounter++;
    }  

    return result;
}

Upvotes: 13

Paolo Falabella
Paolo Falabella

Reputation: 25834

If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:

var  oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0

Upvotes: 13

auraham
auraham

Reputation: 1741

You can use a generic collection, like List<>

List<string> list = new List<string>();

// add
list.Add("element");

// remove
list.Remove("element");

Upvotes: 0

Brad
Brad

Reputation: 12245

You should take a look at the List object. Lists tend to be better at changing dynamically like you want. Arrays not so much...

Upvotes: 0

M.Babcock
M.Babcock

Reputation: 18965

Since arrays implement IEnumerable<T> you can use Concat:

string[] strArr = { "foo", "bar" };
strArr = strArr.Concat(new string[] { "something", "new" });

Or what would be more appropriate would be to use a collection type that supports inline manipulation.

Upvotes: 6

Kendall Frey
Kendall Frey

Reputation: 44316

Use List<string> instead of string[].

List allows you to add and remove items with good performance.

Upvotes: 3

Oded
Oded

Reputation: 498904

Don't use an array - use a generic List<T> which allows you to add items dynamically.

If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.

Upvotes: 6

Related Questions