A list is a collection composed of objects that are strongly typed. Lists like arrays, have indices in which they can be accessed by.
Create a list
A list is created in the following manner:
List <DataType> nameOfList = new List<DataType>();
So if we want to create a list of integer numbers, we do the following:
List<int> numbers = new List<int>();
Add elements to a list
Using the list called numbers
above, we can add numbers to the list using the Add
method. The Add
method is a built-in method to add elements to a list.
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
numbers.Add(4);
We can declare and initialize the list above in one step:
List<int> numbers new List<int> { 1, 2, 3, 4 };
Adding an array to a list
int[] moreNumbers = new int[2]{5, 6};
numbers.AddRange(moreNumbers);
Adding objects to a list
If you have objects of a class you can also add those to a list:
var employees = new List<Employee>(){
new Employee(){Id=341, FirstName="Tom", LastName="Jones"},
new Employee(){Id=453, FirstName="Peter", LastName="Johnson"},
new Employee(){Id=576, FirstName="Lisa", LastName="Mancini"}
};
Access a list
As stated above a list can be accessed like an array using its index. Using the numbers
example above, we would access the elements of that list like so:
Console.WriteLine(numbers[0]); //1
Console.WriteLine(numbers[1]); //2
Console.WriteLine(numbers[2]); //3
Console.WriteLine(numbers[3]); //4
Using LINQ to access a list
We can use LINQ and query a list. Let’s say we want to query the employees list above for Lisa, we would do that the following way:
var employee = from e in employees where e.FirstName == "Lisa" select e;