-
Notifications
You must be signed in to change notification settings - Fork 6k
add List collection quick start #3384
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
ab75735
0407347
79591c7
ed85ada
ae87d72
3954b8a
3274168
9b07ee2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 # | ||
|
||
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. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
``` | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.