C #: Is it possible to assign an implicit Arraylist?

I would like to populate the arraylist by specifying a list of values ​​just like I would an integer array, but I'm not sure how to do this without calling the add method again.

For example, I want to assign {1, 2, 3, "string1", "string2"} to arraylist. I know that for other arrays you can do the job as follows:

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 does not implement the ICollection interface.

+3
source share
5 answers

There is a ctor in the list of arrays that accepts an ICollection, which is implemented by the Array class.

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

# .

# 3.0 ,

.

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

, , AddRange, , , .

+14

, ArrayList, , .

, , , , .

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

# 2.0 ( , ).

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

int [] , .

+1

, # 3.0, . temp, : 1.1/2.0:

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

( , ...)

The closest I found to what I want is to use 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 enough for what I need, but I was hoping it could be done on one line without creating a temporary array, as someone else had suggested.

0
source

Source: https://habr.com/ru/post/1697081/


All Articles