C# dynamically add elements to arrays
background:
Now we need to loop into the array, but the arrays in C# do not support dynamic addition of elements and can only create arrays of fixed size. How to solve this problem?
Referring to the online information, I personally think the solution is better: use the generic list<T>, first save the element into the list, and finally use ToArray() to convert it into an array.
Array to list< string >
string[] strArray = new string[]{str1,str2,str3}; //You can also string[] strArray = {str1,str2,str3};List<string> strList = new List<string>(strArray);
< string > to string array
List<string> strList = new List<string>(); for(int i = 0; i < 3; i++) { ("str"+i);//Loop to add elements} string[] strArray = ();//strArray=[str0,str1,str2]
C# dynamically add elements using List
Arrays in C# do not support dynamic addition of elements, and can only create arrays of fixed size.
Solution: You can use List
List<string> result = new List<string>(); for (int i = 0; i < 5; i++ ) { (()); }
It can also be converted to array type later:
string[] strArray = ();
Attachment: Iterate over elements in List
foreach (T element in mList) { (element); }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.