Learn to manage data collections using the generic list type
This tutorial teaches you C# interactively, using your browser to write C# code and see the results of compiling and running your code. It contains a series of lessons that create, modify, and explore collections and arrays.
Tip
To paste a code snippet inside the focus mode you should use your keyboard shortcut (Ctrl + v, or cmd + v).
Create lists
Run the following code in the interactive window. Select the Enter focus mode button. Then, type the following code block in the interactive window (replace <name>
with your name) and select Run:
var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
If you are running this on your environment, you should follow the instructions for the local version instead.
You've created a list of strings, added three names to that list, and printed out the names in all CAPS. You're using concepts that you've learned in earlier tutorials to loop through the list.
The code to display names makes use of the string interpolation feature. When you precede a string
with the $
character, you can embed C# code in the string declaration. The actual string replaces that C# code with the value it generates. In this example, it replaces the {name.ToUpper()}
with each name, converted to capital letters, because you called the String.ToUpper method.
Let's keep exploring.
Modify list contents
The collection you created uses the List<T> type. This type stores sequences of elements. You specify the type of the elements between the angle brackets.
One important aspect of this List<T> type is that it can grow or shrink, enabling you to add or remove elements. You can see the results by modifying the contents after you've displayed its contents. Add the following code below the code you've already written (below the loop that prints the contents):
Console.WriteLine();
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
You've added two more names to the end of the list. You've also removed one as well. The output from this block of code shows the initial contents, then prints a blank line and the new contents.
The List<T> enables you to reference individual items by index as well. You access items using the [
and ]
tokens. Add the following code below what you've already written and try it:
Console.WriteLine($"My name is {names[0]}.");
Console.WriteLine($"I've added {names[2]} and {names[3]} to the list.");
You're not allowed to access past the end of the list. You can check how long the list is using the Count property. Add the following code to try it:
Console.WriteLine($"The list has {names.Count} people in it");
Select Run again to see the results. In C#, indices start at 0, so the largest valid index is one less than the number of items in the list.
Search and sort lists
Our samples use relatively small lists, but your applications may often create lists with many more elements, sometimes numbering in the thousands. To find elements in these larger collections, you need to search the list for different items. The IndexOf method searches for an item and returns the index of the item. If the item isn't in the list, IndexOf
returns -1
. Try it to see how it works. Add the following code below what you've written so far:
var index = names.IndexOf("Felipe");
if (index != -1)
{
Console.WriteLine($"The name {names[index]} is at index {index}");
}
var notFound = names.IndexOf("Not Found");
Console.WriteLine($"When an item is not found, IndexOf returns {notFound}");
You may not know if an item is in the list, so you should always check the index returned by IndexOf. If it is -1
, the item was not found.
The items in your list can be sorted as well. The Sort method sorts all the items in the list in their normal order (alphabetically for strings). Add this code and run again:
names.Sort();
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
Lists of other types
You've been using the string
type in lists so far. Let's make a List<T> using a different type. Let's build a set of numbers. Delete the code you wrote so far, and replace it with the following code:
var fibonacciNumbers = new List<int> {1, 1};
That creates a list of integers, and sets the first two integers to the value 1. The Fibonacci Sequence, a sequence of numbers, starts with two 1s. Each next Fibonacci number is found by taking the sum of the previous two numbers. Add this code:
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
fibonacciNumbers.Add(previous + previous2);
foreach(var item in fibonacciNumbers)
{
Console.WriteLine(item);
}
Press Run to see the results;
Challenge
See if you can put together some of the concepts from this and earlier lessons. Expand on what you've built so far with Fibonacci Numbers. Try and write the code to generate the first 20 numbers in the sequence. (As a hint, the 20th Fibonacci number is 6765.)
Complete challenge
Did you come up with something like this?
var fibonacciNumbers = new List<int> {1, 1};
while (fibonacciNumbers.Count < 20)
{
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
fibonacciNumbers.Add(previous + previous2);
}
foreach(var item in fibonacciNumbers)
{
Console.WriteLine(item);
}
With each iteration of the loop, you're taking the last two integers in the list, summing them, and adding that value to the list. The loop repeats until you've added 20 items to the list.
Congratulations!
You've completed the list interactive tutorial. That's the final introduction to C# interactive tutorial. You can visit the .NET site to download the .NET SDK, create a project on your machine, and keep coding. The "Next steps" section brings you back to these tutorials.
You can learn more about .NET collections in the following articles:
Have an issue with this section? If so, please give us some feedback so we can improve this section.