Question

I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.

For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:

int[] IntArray = {1,2,3};

Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.

Was it helpful?

Solution

Array list has ctor which accepts ICollection, which is implemented by the Array class.

object[] myArray = new object[] {1,2,3,"string1","string2"};
ArrayList myArrayList = new ArrayList(myArray);

OTHER TIPS

Depending on the version of C# you are using, you have different options.

C# 3.0 has collection initializers, detail at Scott Gu's Blog

Here is an example of your problem.

ArrayList list = new ArrayList {1,2,3};

And if you are initializing a collection object, most have constructors that take similar components to AddRange, although again as you mentioned this may not be an option.

Your comments imply you chose ArrayList because it was the first component you found.

Assuming you are simply looking for a list of integers, this is probably the best way of doing that.

List<int> list = new List<int>{1,2,3};

And if you are using C# 2.0 (Which has generics, but not collection initializers).

List<int> list = new List<int>(new int[] {1, 2, 3});

Although the int[] format may not be correct in older versions, you may have to specify the number of items in the array.

I assume you're not using C# 3.0, which has collection initializers. If you're not bothered about the overhead of creating a temp array, you could do it like this in 1.1/2.0:

ArrayList list = new ArrayList(new object[] { 1, 2, 3, "string1", "string2"});

(kind of answering my own question but...)

The closest thing I've found to what I want is to make use of the ArrayList.Adapter method:

object[] values = { 1, 2, 3, "string1", "string2" };
ArrayList AL = new ArrayList();
AL = ArrayList.Adapter(values);

//or during intialization
ArrayList AL2 = ArrayList.Adapter(values);

This is sufficient for what I need, but I was hoping it could be done in one line without creating the temporary array as someone else had suggested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top