Array Arrays of Any Size in C #

I want to define an array of strings, but I do not know the number of strings that I will need to store in it. Can I define such an array and how to insert it into it?

+3
source share
6 answers

Better to use a List:

List<string> names = new List<string>();
names.Add(name); ///whatever string you want to insert

Later, if you need an array of names, call:

string[] arr = names.ToArray();

If you need to use an array of strings, you must know the size of the advance. If you don't know the size, you can initialize an array of some length by default (say 10). What you need to do is:

  • Keep the number of rows already added to the array
  • , (, 15) .
  • , , (.. , )

, ,

+9

List<string>, .

List<string> myList = new List<string>();
myList.Add("string1");
myList.Add("string2");

, :

string[] stringArray = myList.ToArray();

, , , ( ).

+6

List. , , , . , , List .

int capacity = 3;
var listOfNames = List<string>(/* optional */ capacity);
listOfNames.Add("My Name 1");
listOfNames.Add("My Name 2");
listOfNames.Add("My Name 3");

var namesArray = listOfNames.ToArray();

namesArray , - .

, , List.

0

, ( ), , .

List<String> l = new List<String>();

l.Add("your string here");

... , :

foreach(string i in l)
{
   // Do something with each item (i);
}

... :

String[] a =
     l.ToArray();
0

List<T>. .

var list = new List<string>();
list.Add("string1");

, , List<T> ToArray().

List<T> . , . , , .

0

ArrayList .

ArrayList alist = new ArrayList();

alist.Add(1); alist.Add(2)

0

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


All Articles