tags:

views:

2970

answers:

6

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.

+2  A: 

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

object[] myArray = new new object[] {1,2,3,"string1","string2");
ArrayList myArrayList = new ArrayList(myArray);
Sunny
+3  A: 

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.

Guvante
A: 

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"});
Matt Howells
A: 

(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.

Lyndon
+1  A: 

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.

Guvante
A: 

try to add similer types in arraylist.

http://csharp.net-informations.com/collection/csharp-arraylist.htm

If you want to know more about implicit conversion :

http://csharp.net-informations.com/language/csharp-type-conversions.htm

bton.

bolton