नोट
इस पृष्ठ तक पहुंच के लिए प्राधिकरण की आवश्यकता होती है। आप साइन इन करने या निर्देशिकाएँ बदलने का प्रयास कर सकते हैं।
इस पृष्ठ तक पहुंच के लिए प्राधिकरण की आवश्यकता होती है। आप निर्देशिकाएँ बदलने का प्रयास कर सकते हैं।
This introductory tutorial provides an introduction to the C# language and the basics of the System.Collections.Generic.List<T> class.
This tutorial teaches you C#. You write C# code and see the results of compiling and running that code. It contains a series of lessons that create, modify, and explore collections. You work primarily with the List<T> class.
In this tutorial, you:
- Launch a GitHub Codespace with a C# development environment.
- Create different types of lists.
- Modify list contents.
- Search and sort lists.
Prerequisites
You must have one of the following:
- A GitHub account to use GitHub Codespaces. If you don't already have one, you can create a free account at GitHub.com.
- A computer with the following tools installed:
- The .NET 10 SDK.
- Visual Studio Code.
- The C# DevKit.
A basic list example
To start a GitHub Codespace with the tutorial environment, open a browser window to the tutorial codespace repository. Select the green Code button, and the Codespaces tab. Then select the + sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace instead of creating a new one.
When your codespace loads, create a new file in the tutorials folder named lists.cs.
Open your new file.
Type or copy the following code into lists.cs:
List<string> names = ["<name>", "Ana", "Felipe"]; foreach (var name in names) { Console.WriteLine($"Hello {name.ToUpper()}!"); }Run the code by typing the following command in the terminal window:
cd tutorials dotnet lists.cs
You created a list of strings, added three names to that list, and printed the names in all caps. You're using concepts that you 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 displayed its contents.
Add the following code after the code you already wrote (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 added two more names to the end of the list. You 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 after what you already wrote 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 by using the Count property.
Add the following code:
Console.WriteLine($"The list has {names.Count} people in it");Type
dotnet lists.csagain in the terminal window 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.
For more information about indices, see the Explore indexes and ranges article.
Search and sort lists
Our samples use relatively small lists, but your applications might 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 after what you wrote so far:
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}"); }You might not know if an item is in the list, so you should always check the index returned by IndexOf. If it's
-1, the item wasn't found.You can also sort the items in your list. 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
So far, you've been using the string type in lists. Let's make a List<T> using a different type. Let's build a set of numbers.
Add the following code at the end of your source file:
List<int> fibonacciNumbers = [1, 1];That code 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 1's. 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); }Type
dotnet lists.csin the terminal window to see the results.
Challenge
See if you can put together some of the concepts from this and earlier lessons. Expand on what you built so far with Fibonacci Numbers. Try to write the code to generate the first 20 numbers in the sequence. (As a hint, the 20th Fibonacci number is 6765.)
Did you come up with something like this?
List<int> fibonacciNumbers = [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 take the last two integers in the list, sum them, and add that value to the list. The loop repeats until you add 20 items to the list.
You completed the list tutorial. You can learn more about .NET collections in the following articles:
Cleanup resources
GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the .NET site to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to your Codespaces. You should see a list of your codespaces in the window. Select the three dots (...) in the entry for the learn tutorial codespace and select delete.