Question about array
Hi guys
How to add and remove elements in array ? its kinda hard I wanna know the basic one.
Arr = new string[] {"love","hate","girl","head","to","me"};
here's my array
Answer by phxvyper · Dec 07, 2016 at 07:47 AM
in C# you cannot mutate an array like this. If you want a dynamic array I suggest looking at List
var someList = new List<string>(new[] { "love","hate","girl","head","to","me" });
// the list is now { "love","hate","girl","head","to","me","another" }
someList.Add("another");
// the list is now { "love","girl","head","to","me","another" }
someList.RemoveAt(1);
Answer by lspence812 · Dec 07, 2016 at 07:19 PM
You can also use an ArrayList if all elements will be of the same type (i.e. string).
ArrayList arr = new ArrayList();
arr.AddRange(new string[] { "love", "hate", "girl", "head", "to", "me" });
// print the contents of the ArrayList
names;
// adding another element to the ArrayList
names.Add("boy");
// removing an element from the ArrayList
names.Remove("head");
Both ArrayList and Generic Lists are collections; however, it is better to use a Generic List as it performs better and can contain mixed types.
Cool .. if I have
arr.AddRange(new string[] { "love", "hate", "girl", "head", "to", "me" }); ArrayList arr = new ArrayList();
and I have this thing Arrs= new string[] {"happy","damn","boy","attack","be","cool"};
then how can I add data from Arrs to my arraList arr?
For example my arr is empty. Then I want to fetch some data from Arrs. Ill get 4 elements from it randomly .. is it possible ?
You could add a value from your Array to the ArrayList by providing the index of your Array value.
arr.Add(Arrs[3]);
The above would add "attack" to the ArrayList giving you the values: "love", "hate", "girl", "head", "to", "me", "attack"
Your answer
![](https://koobas.hobune.stream/wayback/20220612102217im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array (List) with multiple variable types? 2 Answers
Array Inspector 0 Answers
Get all Children of an Object with a certain component 0 Answers
How to perform this Word Game 0 Answers
Keeping track of dynamic positions of items in a grid using List/Array? 0 Answers