Creating a list in C# is an essential part of programming. A list is a data structure that can store a collection of items of the same data type. In C#, the List class
Step 1: Create a new project in Visual Studio
First, you need to create a new project in Visual Studio. Open Visual Studio, click “File” and then “New Project”. Select “Console App (.NET Core)” and give your project a name.
Step 2: Import the list namespace
Before you can use the List class, you must import the System.Collections.Generic namespace. Add the following line of code to the top of your file:
using System.Collections.Generic;
Step 3: Create a new list
To create a new list, you must declare a variable of type List
List<int> numbers = new List<int>();
This creates an empty list of integers called “numbers”.
Step 4: Add items to the list
To add items to the list, you can use the Add method. For example, to add the numbers 42, 66, 78 and 96 to the list, you would write:
numbers.Add(42); numbers.Add(66); numbers.Add(78); numbers.Add(96);
You can add as many items to the list as you like.
Step 5: Access items in the list
To access an item in a list, you can use the index operator []. For example, to access the first item in the list, you would write:
int firstItem = numbers[0];
This will assign the value of the first item in the list to the “firstItem” variable.
Step 6: Remove items from the list
To remove an item from the list, you can use the remove method. For example, to remove the first item from the list, you would write:
numbers.Remove(numbers[0]);
This will remove the first item from the list.
Step 7: Count the number of items in the list
To count the number of items in a list, you can use the Count property. For example, to get the number of items in the “Numbers” list, you would write:
int count = numbers.Count;
This will assign the number of items in the list to the “count” variable.
Step 8: Repeat the items on the list
To iterate over the items in a list, you can use a for loop. For example, to print all the items in the “numbers” list, you would write:
foreach (int number in numbers) { Console.WriteLine(number); }
This will print all the items in the list, one by one.
Summary
Creating a list in C# is a simple process that involves declaring a variable of type List