What is a List?
A list is a collection of data.Example
- Create a new list
//initialize an empty list for objects with type of INTEGERList<int> numbers = new List<int>();
//initialize an empty list for objects with type of STRING
List<string> names = new List<string>();
//initialize a list with objects type of INTEGER
List<int> numbers = new List<int>() {1,2,3,4}; //List with 4 integer elements
//initialize a list with objects type of STRINGList<string> names = new List<string>() {"Dad","Mum","Child"}; //List with 3 string elements
- Add elements to a list
//add one element at the end numbers.Add(5);
//add a collection of new elements at the end
numbers.AddRange(new List<int>() { 6, 7, 8 });
//add one element at the end
names.Add("Child2");
//add a collection of new elements at the end
names.AddRange(new List<string>() { "Child3", "Child4" });
//add one element at a defined position
numbers.Insert(8, 9);
//add one element at a defined position
names.Insert(6, "Child5");
//add a collection of new elements starting at a defined position
numbers.InsertRange(9, new List<int>() { 10, 11, 12 });
//add a collection of new elements starting at a defined position
names.InsertRange(7, new List<string>() { "Child6", "Child7" });
- Remove elements from a list
//remove the object with the value 8 from the list numbers.Remove(8);
//remove the opbject with the value Child from the list
names.Remove("Child");
//remove object at position 3
numbers.RemoveAt(3);
//remove 2 elements, starting at position 4
numbers.RemoveRange(4, 2);