Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 219 additions & 0 deletions docs/csharp/quick-starts/arrays-and-collections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
---
title: Quick Start - Collections - C# Guide
description: Learn C# by exploring the List collection in this quick start.
keywords: C#, Get Started, tutorial, collections, List
author: billwagner
ms.author: wiwagn
ms.date: 10/13/2017
ms.topic: article
ms.prod: .net
ms.technology: devlang-csharp
ms.devlang: csharp
---
# C# Quick start: Collections #
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not hooked up to the TOC. Should it be or not?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For now, I'm not adding it. I'd like to learn which has higher satisfaction in the user study: the local version, or the online / interactive version. Or, it may be both.

I'll update after the user study, based on what we learn.


This tutorial provides an introduction to the C# language and the basics of the <xref:System.Collections.Generic.List%601>
class.

## A simple list example.

> [!NOTE]
> If you're starting from the code you wrote in [dot.net](https://dot.net/), you already have the code written in this section. Jump to [Modify list contents](#modify-list-contents).

This lesson assumes you've finished the online quick starts, and you've installed the [.NET Core SDK](http://dot.net/core) and [Visual Studio Code](https://code.visualstudio.com/).

Create a directory named **list-quickstart**. Make that the current directory and run `dotnet new console`.

Open **Program.cs** in your favorite editor, and replace the existing code with the following:

```csharp
using System;
using System.Collections.Generic;

namespace list_quickstart
{
class Program
{
static void Main(string[] args)
{
var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}
}
}
}
```

Replace `<name>` with your name. Save **Program.cs**. Type `dotnet run` in your console window to try it.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't give this instruction on the interactive one. Should you?


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 <xref:System.String.ToUpper%2A> method.

Let's keep exploring.

## Modify list contents

The collection you created uses the <xref:System.Collections.Generic.List%601> type. This type stores sequences of elements. You specify the type of the elements between the angle brackets.

One important aspect of this <xref:System.Collections.Generic.List%601> type is that it can grow or shrink, enabling you to add or remove elements. Add this code before the closing `}` in the `Main` method:

```csharp
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. Save the file, and type `dotnet run` to try it.

The <xref:System.Collections.Generic.List%601> enables you to reference individual items by **index** as well. You place the index between `[` and `]` tokens following the list name. C# uses 0 for the first index. Add this code directly below the code you just added and try it:

```csharp
Console.WriteLine($"My name is {names[0]}");
Console.WriteLine($"I've added {names[2]} and {names[3]} to the list");
```

You cannot access an index beyond the end of the list. Remember that indices start at 0, so the largest valid index is one less than the number of items in the list. You can check how long the list is using the <xref:System.Collections.Generic.List%601.Count%2A> property. Add the following code at the end of the Main method:

```csharp
Console.WriteLine($"The list has {names.Count} people in it");
```

Save the file, and type `dotnet run` again to see the results.

## 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 <xref:System.Collections.Generic.List%601.IndexOf%2A> method searches for an item and returns the index of the item. Add this code to the bottom of your `Main` method:

```csharp
var index = names.IndexOf("Felipe");
if (index == -1)
{
Console.WriteLine($"When an item is not found, IndexOf returns {index}");
} else
{
Console.WriteLine($"The name {names[index]} is at index {index}");
}

index = names.IndexOf("Not Found");
if (index == -1)
{
Console.WriteLine($"When an item is not found, IndexOf returns {index}");
} else
{
Console.WriteLine($"The name {names[index]} is at index {index}");

}
```

The items in your list can be sorted as well. The <xref:System.Collections.Generic.List%601.Sort%2A> method sorts all the items in the list in their normal order (alphabetically in the case of strings). Add this code to the bottom of our `Main` method:

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

Save the file and type `dotnet run` to try this latest version.

Before you start the next section, let's move the current code into a separate method. That makes it easier to start working with a new example. Rename your `Main` method to `WorkingWithStrings` and write a new `Main` method that calls `WorkingWithStrings`. When you have finished, your code should look like this:

```csharp
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should you show the whole listing with namespace and using statements?

using System;
using System.Collections.Generic;

namespace list_quickstart
{
class Program
{
static void Main(string[] args)
{
WorkingWithStrings();
}

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

Console.WriteLine();
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");
foreach (var name in names)
{
Console.WriteLine($"Hello {name.ToUpper()}!");
}

Console.WriteLine($"My name is {names[0]}");
Console.WriteLine($"I've added {names[2]} and {names[3]} to the list");

Console.WriteLine($"The list has {names.Count} people in it");

var index = names.IndexOf("Felipe");
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}");

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 <xref:System.Collections.Generic.List%601> using a different type. Let's build a set of numbers.

Add the following to the bottom of your new `Main` method:

```csharp
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:

```csharp
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];

fibonacciNumbers.Add(previous + previous2);

foreach(var item in fibonacciNumbers)
Console.WriteLine(item);
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code needs a little bit more explanation -- 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, and then repeating the procedure.


Save the file and type `dotnet run` to see the results.

> [!TIP]
> To concentrate on just this section, you can comment out the code that calls `WorkingWithStrings();`. Just put two `/` characters in front of the call like this: `// WorkingWithStrings();`.

## Challenge
See if you can put together some of the lessons 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.

## Complete challenge

You can see an example solution by [looking at the finished sample code on GitHub](https://github.com/dotnet/docs/tree/master/samples/csharp/list-quickstart/Program.cs)

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

You can learn more about working with the `List` type in the
[.NET Guide](../../standard/index.md) topic on [collections](../../standard/collections/index.md). You'll also learn about many other collection types.
2 changes: 2 additions & 0 deletions docs/csharp/quick-starts/branches-and-loops.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ metadata:
level: Beginner
displayType: two-column
interactive: csharp
nextTutorialHref: arrays-and-collections
nextTutorialTitle: Arrays and colletions in C#
items:
- durationInMinutes: 1
content: |
Expand Down
2 changes: 1 addition & 1 deletion docs/csharp/quick-starts/hello-world.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ items:
- title: Run your first C# program
durationInMinutes: 2
content: |
Run the following code in the interactive window. To do that, type code block in the interactive window and click the **Run** button:
Run the following code in the interactive window. To do that, type the following code block in the interactive window and click the **Run** button:

```csharp
Console.WriteLine("Hello World!");
Expand Down
15 changes: 12 additions & 3 deletions docs/csharp/quick-starts/index.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
---
title: Quick Starts - C# Guide
description: Learn C# in your browser
description: Learn C# in your browser, and get started with your own development environment
keywords: C#, Get Started, Lessons, Interactive
author: billwagner
ms.author: wiwagn
ms.date: 09/18s/2017
ms.date: 09/18/2017
ms.topic: article
ms.prod: .net
ms.technology: devlang-csharp
Expand Down Expand Up @@ -42,5 +42,14 @@ different paths of code based on the values stored in variables. You'll learn th
basics of control flow, which is the basics of how programs make decisions and choose
different actions.

This beginner lesson assumes that you have finished the [Hello World](hello-world.yml) and
This beginning lesson assumes that you have finished the [Hello World](hello-world.yml) and
[Numbers in C#](numbers-in-csharp.yml) lessons.

## [List collection](list-collection.yml)

The [List collection](list-collection.yml) lesson gives you
a tour of the List collection type that stores sequences of data. You'll learn how to add and remove items, search for items, and remove items and sort the lists. You'll explore different kinds of lists.

This beginning lesson assumes that you have finished the quick starts listed above.

You can also try this lesson [using the own develoment environment on your machine](arrays-and-collections.md).
Loading