了解如何使用泛型列表类型管理数据集合Learn to manage data collections using the generic list type

本介绍性教程介绍了 C# 语言和 List<T> 类的基础知识。This introductory tutorial provides an introduction to the C# language and the basics of the List<T> class.

本教程要求你有一台可用于开发的计算机。This tutorial expects you to have a machine you can use for development. .NET 教程 Hello World 10 分钟入门介绍了如何在 Windows、Linux 或 macOS 上设置本地开发环境。The .NET tutorial Hello World in 10 minutes has instructions for setting up your local development environment on Windows, Linux, or macOS. 熟悉开发工具不仅简要概述了将用到的命令,还收录了详细信息链接。A quick overview of the commands you'll use is in Become familiar with the development tools, with links to more details.

基本列表示例A basic list example

创建名为 list-tutorial 的目录。Create a directory named list-tutorial. 将新建的目录设为当前目录,并运行 dotnet new consoleMake that the current directory and run dotnet new console.

在常用编辑器中,打开 Program.cs ,并将现有代码替换为以下代码:Open Program.cs in your favorite editor, and replace the existing code with the following:

using System;
using System.Collections.Generic;

namespace list_tutorial
{
    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()}!");
            }
        }
    }
}

<name> 替换为自己的名称。Replace <name> with your name. 保存 Program.cs 。Save Program.cs. 在控制台窗口中键入 dotnet run,试运行看看。Type dotnet run in your console window to try it.

刚刚创建了一个字符串列表,并向其中添加了三个名称,再输出了全部大写的名称。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 tutorials to loop through the list.

用于显示名称的代码使用字符串内插功能。The code to display names makes use of the string interpolation feature. 如果 string 前面有 $符号,可以在字符串声明中嵌入 C# 代码。When you precede a string with the $ character, you can embed C# code in the string declaration. 实际字符串使用自己生成的值替换该 C# 代码。The actual string replaces that C# code with the value it generates. 在此示例中,{name.ToUpper()} 被替换为各个转换为大写字母的名称,因为调用了 ToUpper 方法。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.

修改列表内容Modify list contents

创建的集合使用 List<T> 类型。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.

List<T> 类型的一个重要方面是,既可以扩大,也可以收缩,方便用户添加或删除元素。One important aspect of this List<T> type is that it can grow or shrink, enabling you to add or remove elements. Main 方法的右 } 前添加以下代码:Add this code before the closing } in the Main method:

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. 保存此文件,并键入 dotnet run,试运行看看。Save the file, and type dotnet run to try it.

借助 List<T>,还可以按索引 引用各项。The List<T> enables you to reference individual items by index as well. 索引位于列表名称后面的 [] 令牌之间。You place the index between [ and ] tokens following the list name. C# 对第一个索引使用 0。C# uses 0 for the first index. 将以下代码添加到刚才添加的代码的正下方,并试运行看看:Add this code directly below the code you just added and try it:

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. 请注意,索引是从 0 开始编制,因此最大有效索引是用列表项数减 1 计算得出。Remember that indices start at 0, so the largest valid index is one less than the number of items in the list. 可以使用 Count 属性确定列表长度。You can check how long the list is using the Count property. 在 Main 方法的末尾,添加以下代码:Add the following code at the end of the Main method:

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

保存此文件,并再次键入 dotnet run 看看结果如何。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. IndexOf 方法可搜索项,并返回此项的索引。The IndexOf method searches for an item and returns the index of the item. 将以下代码添加到 Main 方法的底部:Add this code to the bottom of your Main method:

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. Sort 方法按正常顺序(按字母顺序,如果是字符串的话)对列表中的所有项进行排序。The Sort method sorts all the items in the list in their normal order (alphabetically in the case of strings). 将以下代码添加到 Main 方法的底部:Add this code to the bottom of our Main method:

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

保存此文件,并键入 dotnet run,试运行此最新版程序。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. Main 方法重命名为 WorkingWithStrings,并编写调用 WorkingWithStrings 的新 Main 方法。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:

using System;
using System.Collections.Generic;

namespace list_tutorial
{
    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

到目前为止,大家一直在列表中使用 string 类型。You've been using the string type in lists so far. 接下来,将让 List<T> 使用其他类型。Let's make a List<T> using a different type. 那就生成一组数字吧。Let's build a set of numbers.

将以下代码添加到新 Main 方法的底部:Add the following to the bottom of your new Main method:

var fibonacciNumbers = new List<int> {1, 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);

保存此文件,并键入 dotnet run 看看结果如何。Save the file and type dotnet run to see the results.

提示

为了能够集中精力探究此部分,可以注释掉调用 WorkingWithStrings(); 的代码。To concentrate on just this section, you can comment out the code that calls WorkingWithStrings();. 只需在此调用前添加两个 / 字符即可,如 // WorkingWithStrings();Just put two / characters in front of the call like this: // WorkingWithStrings();.

挑战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. 试着编写代码,生成此序列中的前 20 个数字。Try to write the code to generate the first 20 numbers in the sequence. (作为提示,第 20 个斐波纳契数是 6765。)(As a hint, the 20th Fibonacci number is 6765.)

完成挑战Complete challenge

可以查看 GitHub 上的完成示例代码,了解示例解决方案。You can see an example solution by looking at the finished sample code on GitHub.

在循环的每次迭代中,取此列表中的最后两个整数进行求和,并将计算出的总和值添加到列表中。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. 循环会一直重复运行到列表中有 20 个项为止。The loop repeats until you've added 20 items to the list.

恭喜!已完成“列表集合”教程。Congratulations, you've completed the list tutorial. 可以在自己的开发环境中继续学习类简介教程。You can continue with the Introduction to classes tutorial in your own development environment.

若要详细了解如何使用 List 类型,可以参阅有关集合.NET 指南主题。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.