Си шарп класс list

Узнайте, как управлять коллекциями данных с помощью List в C#

Это вводное руководство содержит общие сведения о языке C# и классе List .

Предварительные требования

Для работы с руководством вам потребуется компьютер, настроенный для разработки в локальной среде. Инструкции по установке и общие сведения о разработке приложений в .NET см. в статье Настройка локальной среды .

Если вы предпочитаете выполнять код без настройки локальной среды, ознакомьтесь с интерактивной версией этого руководства в браузере.

Пример простого списка

Создайте каталог с именем list-tutorial. Откройте этот каталог и выполните команду dotnet new console .

В шаблонах C# для .NET 6 используются операторы верхнего уровня. Приложение может не соответствовать коду, приведенному в этой статье, если вы уже выполнили обновление до .NET 6. Дополнительные сведения см. в статье Новые шаблоны C# для создания инструкций верхнего уровня.

Пакет SDK для .NET 6 также добавляет набор неявных global using директив для проектов, использующих следующие пакеты SDK:

Эти неявные директивы global using включают наиболее распространенные пространства имен для соответствующего типа проектов.

Откройте Program.cs в любом редакторе и замените существующий код следующим:

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

Замените собственным именем. Сохраните Program.cs. Введите в окне консоли команду dotnet run для тестирования.

Вы создали список строк, добавили три имени в этот список и вывели имена прописными буквами. Для циклического прохода по списку вы примените концепции, которые изучили в предыдущих руководствах.

В коде для отображения имен используется функция интерполяции строк. Если перед string добавить символ $ , код C# можно внедрять в объявление строки. Фактическая строка заменяет код C# генерируемым значением. В этом примере она заменяет именами, буквы каждого из которых преобразованы в прописные, так как вызван метод ToUpper.

Изменение содержимого списка

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

В конец списка добавлены еще два имени. При этом одно имя удалено. Сохраните файл и введите dotnet run для тестирования.

Console.WriteLine($"My name is "); Console.WriteLine($"I've added and to the list"); 

Доступ к индексу за пределами списка получить невозможно. Помните, что индексы начинаются с 0, поэтому максимальный допустимый индекс меньше, чем число элементов в списке. Вы можете проверить, как долго в списке используется свойство Count. Добавьте следующий код в конец программы:

Console.WriteLine($"The list has people in it"); 

Сохраните файл и еще раз введите dotnet run , чтобы просмотреть результаты.

Поиск по спискам и их сортировка

В наших примерах используются сравнительно небольшие списки. Но приложения часто создают списки с гораздо большим количеством элементов, иногда они исчисляются в тысячах. Чтобы найти элементы в таких больших коллекциях, необходимо выполнить поиск различных элементов по списку. Метод IndexOf выполняет поиск элемента и возвращает его индекс. Если элемент отсутствует в списке, IndexOf возвращает -1 . Добавьте этот код в конец программы:

var index = names.IndexOf("Felipe"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > index = names.IndexOf("Not Found"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > 

Кроме того, можно сортировать элементы в списке. Метод Sort сортирует все элементы списка в обычном порядке (строки — в алфавитном). Добавьте этот код в конец программы:

names.Sort(); foreach (var name in names) < Console.WriteLine($"Hello !"); > 

Сохраните файл и введите dotnet run , чтобы протестировать последнюю версию.

Читайте также:  Если сессия установлена то php

Прежде чем перейти к следующему разделу, переместим текущий код в отдельный метод. Это упростит начало работы с новым примером. Поместите весь написанный код в новый метод с именем WorkWithStrings() . Вызовите этот метод в начале кода программы. В результате ваш код должен выглядеть примерно следующим образом:

WorkWithStrings(); void WorkWithStrings() < var names = new List< "", "Ana", "Felipe" >; foreach (var name in names) < Console.WriteLine($"Hello !"); > Console.WriteLine(); names.Add("Maria"); names.Add("Bill"); names.Remove("Ana"); foreach (var name in names) < Console.WriteLine($"Hello !"); > Console.WriteLine($"My name is "); Console.WriteLine($"I've added and to the list"); Console.WriteLine($"The list has people in it"); var index = names.IndexOf("Felipe"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > index = names.IndexOf("Not Found"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > names.Sort(); foreach (var name in names) < Console.WriteLine($"Hello !"); > > 

Списки других типов

Добавьте следующий код в программу после вызова WorkWithStrings() :

var fibonacciNumbers = new List ; 

Будет создан список целых чисел. Для первых двух целых чисел будет задано значение 1. Это два первых значения последовательности Фибоначчи. Каждое следующее число Фибоначчи — это сумма двух предыдущих чисел. Добавьте этот код:

var previous = fibonacciNumbers[fibonacciNumbers.Count - 1]; var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2]; fibonacciNumbers.Add(previous + previous2); foreach (var item in fibonacciNumbers)

Сохраните файл и введите dotnet run , чтобы просмотреть результаты.

Для задач этого раздела вы можете закомментировать код, который вызывает WorkWithStrings(); . Просто поместите два / символа перед вызовом, как показано ниже: // WorkWithStrings(); .

Задача

Попробуйте объединить некоторые идеи из этого и предыдущих занятий. Расширьте код с числами Фибоначчи, который вы создали. Попробуйте написать код для создания первых 20 чисел в последовательности. Подсказка: 20-е число Фибоначчи — 6765.

Выполнение задачи

При каждой итерации цикла суммируются два последних целых числа в списке. Полученное значение добавляется в список. Цикл повторяется, пока в список не будут добавлены 20 элементов.

Поздравляем! Вы выполнили задачи в руководстве по спискам. Можете продолжить изучение дополнительных руководств в своей среде разработки.

Дополнительные сведения о работе с типом List см. в статье Коллекции и структуры данных. Также в нем описаны многие другие типы коллекций.

Источник

Learn to manage data collections using List in C#

This introductory tutorial provides an introduction to the C# language and the basics of the List class.

Prerequisites

The tutorial expects that you have a machine set up for local development. See Set up your local environment for installation instructions and an overview of application development in .NET.

Читайте также:  Java api java lang thread

If you prefer to run the code without having to set up a local environment, see the interactive-in-browser version of this tutorial.

A basic list example

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

The C# templates for .NET 6 use top level statements. Your application may not match the code in this article, if you’ve already upgraded to the .NET 6. For more information see the article on New C# templates generate top level statements

The .NET 6 SDK also adds a set of implicit global using directives for projects that use the following SDKs:

These implicit global using directives include the most common namespaces for the project type.

For more information, see the article on Implicit using directives

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

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

Replace with your name. Save Program.cs. Type dotnet run in your console window to try it.

You’ve created a list of strings, added three names to that list, and printed 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. 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 with each name, converted to capital letters, because you called the ToUpper method.

Modify list contents

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

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.

Console.WriteLine($"My name is "); Console.WriteLine($"I've added and to the list"); 

You can’t 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 Count property. Add the following code at the end of your program:

Console.WriteLine($"The list has 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 IndexOf method searches for an item and returns the index of the item. If the item isn’t in the list, IndexOf returns -1 . Add this code to the bottom of your program:

var index = names.IndexOf("Felipe"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > index = names.IndexOf("Not Found"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > 

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 for strings). Add this code to the bottom of your program:

names.Sort(); foreach (var name in names) < Console.WriteLine($"Hello !"); > 

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

Читайте также:  Php транслитерация имени файла

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. Place all the code you’ve written in a new method called WorkWithStrings() . Call that method at the top of your program. When you finish, your code should look like this:

WorkWithStrings(); void WorkWithStrings() < var names = new List< "", "Ana", "Felipe" >; foreach (var name in names) < Console.WriteLine($"Hello !"); > Console.WriteLine(); names.Add("Maria"); names.Add("Bill"); names.Remove("Ana"); foreach (var name in names) < Console.WriteLine($"Hello !"); > Console.WriteLine($"My name is "); Console.WriteLine($"I've added and to the list"); Console.WriteLine($"The list has people in it"); var index = names.IndexOf("Felipe"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > index = names.IndexOf("Not Found"); if (index == -1) < Console.WriteLine($"When an item is not found, IndexOf returns "); > else < Console.WriteLine($"The name is at index "); > names.Sort(); foreach (var name in names) < Console.WriteLine($"Hello !"); > > 

Lists of other types

You’ve been using the string type in lists so far. Let’s make a List using a different type. Let’s build a set of numbers.

Add the following to your program after you call WorkWithStrings() :

var fibonacciNumbers = new List ; 

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)

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

To concentrate on just this section, you can comment out the code that calls WorkWithStrings(); . Just put two / characters in front of the call like this: // WorkWithStrings(); .

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 to write the code to generate the first 20 numbers in the sequence. (As a hint, the 20th Fibonacci number is 6765.)

Complete challenge

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 continue with additional tutorials in your own development environment.

You can learn more about working with the List type in the .NET fundamentals article on collections. You’ll also learn about many other collection types.

Feedback

Submit and view feedback for

Источник

Оцените статью