Collections in C#

This quick start 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.

You will learn how to...

Create lists

Run the following code in the interactive window. To do that, type the following code block in the interactive window (replace "" with your name) and click the Run button:

var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
  Console.WriteLine($"Hello {name.ToUpper()}!");
}

You've just 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 quick starts to loop through the list.

The code to display names makes use of interpolated strings. 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 ToUpper method.

Let's keep exploring.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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. Add the following code below the code you've already written:

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 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");

Click 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.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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. Try this 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 in the case of strings). Add this code and run again:

names.Sort();
foreach (var name in names)
{
  Console.WriteLine($"Hello {name.ToUpper()}!");
}

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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 this:

var fibonacciNumbers = new List<int> {1, 1};

That creates a list of integers, and sets the first two integers to the value 1. These are the first two values of a Fibonacci Sequence, a sequence of numbers. 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;

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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.)

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

Congratulations!

You've completed the list quick start. This quick start is the final interactive quick start. You can continue these quick starts on your own development environment. Learn the basics of local development and then pick a quick start. You can try this same exercise, move directly to the next quick start, or start again at with the numbers in C# quickstart.

You can learn more about working with the List type in the .NET Guide topic on collections. You'll also learn about many other collection types.

You learned how to...

Contributors

  • dotnet bot
  • Bill Wagner
  • Maira Wenzel