Create list c sharp

Learn to manage data collections using the generic list type

This tutorial teaches you C# interactively, using your browser to write C# code and see the results of compiling and running your code. It contains a series of lessons that create, modify, and explore collections and arrays.

To paste a code snippet inside the focus mode you should use your keyboard shortcut ( Ctrl + v , or cmd + v ).

Create lists

Run the following code in the interactive window. Select the Enter focus mode button. Then, type the following code block in the interactive window (replace with your name) and select Run:

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

If you are running this on your environment, you should follow the instructions for the local version instead.

You’ve 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. 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 String.ToUpper method.

Читайте также:  Javascript присвоить значение label

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. The output from this block of code shows the initial contents, then prints a blank line and the new contents.

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

You’re not allowed to access past the end of the list. You can check how long the list is using the Count property. Add the following code to try it:

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

Select Run again 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.

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 . Try it to see how it works. Add the following code below what you’ve written so far:

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

You may not know if an item is in the list, so you should always check the index returned by IndexOf. If it is -1 , the item was not found.

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 and run again:

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

Lists of other types

var fibonacciNumbers = new List ; 

That 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 1s. 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)

Press Run to see the results;

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

Complete challenge

Did you come up with something like this?

var fibonacciNumbers = new List ; 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)

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 interactive tutorial. That’s the final introduction to C# interactive tutorial. You can visit the .NET site to download the .NET SDK, create a project on your machine, and keep coding. The «Next steps» section brings you back to these tutorials.

You can learn more about .NET collections in the following articles:

Have an issue with this section? If so, please give us some feedback so we can improve this section.

Feedback

Submit and view feedback for

Источник

Коллекции

Хотя в языке C# есть массивы, которые хранят в себе наборы однотипных объектов, но работать с ними не всегда удобно. Например, массив хранит фиксированное количество объектов, однако что если мы заранее не знаем, сколько нам потребуется объектов. И в этом случае намного удобнее применять коллекции. Еще один плюс коллекций состоит в том, что некоторые из них реализует стандартные структуры данных, например, стек, очередь, словарь, которые могут пригодиться для решения различных специальных задач. Большая часть классов коллекций содержится в пространстве имен System.Collections.Generic .

Класс List из пространства имен System.Collections.Generic представляет простейший список однотипных объектов. Класс List типизируется типом, объекты которого будут хранится в списке.

Мы можем создать пустой список:

В данном случае объект List типизируется типом string . А это значит, что хранить в этом списке мы можем только строки.

Можно сразу при создании списка инициализировать его начальными значениями. В этом случае элементы списка помещаются после вызова конструктора в фигурных скобках

В данном случае в список помещаются три строки

Также можно при создании списка инициализировать его элементами из другой коллекции, например, другого списка:

var people = new List() < "Tom", "Bob", "Sam" >; var employees = new List(people);

Можно совместить оба способа:

var people = new List() < "Tom", "Bob", "Sam" >; var employees = new List(people);

В данном случае в списке employees будет четыре элемента ( < "Tom", "Bob", "Sam", "Mike" >) — три добавляются из списка people и один элемент задается при инициализации.

Подобным образом можно работать со списками других типов, например:

List people = new List() < new Person("Tom"), new Person("Bob"), new Person("Sam") >; class Person < public string Name < get;>public Person(string name) => Name = name; >

Установка начальной емкости списка

Еще один конструктор класса List принимает в качестве параметра начальную емкость списка:

Указание начальной емкости списка позволяет в будущем увеличить производительность и уменьшить издержки на выделение памяти при добавлении элементов. Поскольку динамическое добавление в список может приводить на низком уровне к дополнительному выделению памяти, что снижает производительность. Если же мы знаем, что список не будет превышать некоторый размер, то мы можем передать этот размер в качестве емкости списка и избежать дополнительных выделений памяти.

Также начальную емкость можно установить с помощью свойства Capacity , которое имеется у класса List.

Обращение к элементам списка

Как и массивы, списки поддерживают индексы, с помощью которых можно обратиться к определенным элементам:

var people = new List() < "Tom", "Bob", "Sam" >; string firstPerson = people[0]; // получаем первый элемент Console.WriteLine(firstPerson); // Tom people[0] = "Mike"; // изменяем первый элемент Console.WriteLine(people[0]); // Mike

Длина списка

С помощью свойства Count можно получить длину списка:

var people = new List() < "Tom", "Bob", "Sam" >; Console.WriteLine(people.Count); // 3

Перебор списка

C# позволяет осуществить перебор списка с помощью стандартного цикла foreach :/p>

var people = new List() < "Tom", "Bob", "Sam" >; foreach (var person in people) < Console.WriteLine(person); >// Вывод программы: // Tom // Bob // Sam

Также можно использовать другие типы циклов и в комбинации с индексами перебирать списки:

var people = new List() < "Tom", "Bob", "Sam" >; for (int i = 0; i

Методы списка

Среди его методов можно выделить следующие:

  • void Add(T item) : добавление нового элемента в список
  • void AddRange(IEnumerable collection) : добавление в список коллекции или массива
  • int BinarySearch(T item) : бинарный поиск элемента в списке. Если элемент найден, то метод возвращает индекс этого элемента в коллекции. При этом список должен быть отсортирован.
  • void CopyTo(T[] array) : копирует список в массив array
  • void CopyTo(int index, T[] array, int arrayIndex, int count) : копирует из списка начиная с индекса index элементы, количество которых равно count, и вставляет их в массив array начиная с индекса arrayIndex
  • bool Contains(T item) : возвращает true , если элемент item есть в списке
  • void Clear() : удаляет из списка все элементы
  • bool Exists(Predicate match) : возвращает true , если в списке есть элемент, который соответствует делегату match
  • T? Find(Predicate match) : возвращает первый элемент, который соответствует делегату match. Если элемент не найден, возвращается null
  • T? FindLast(Predicate match) : возвращает последний элемент, который соответствует делегату match. Если элемент не найден, возвращается null
  • List FindAll(Predicate match) : возвращает список элементов, которые соответствуют делегату match
  • int IndexOf(T item) : возвращает индекс первого вхождения элемента в списке
  • int LastIndexOf(T item) : возвращает индекс последнего вхождения элемента в списке
  • List GetRange(int index, int count) : возвращает список элементов, количество которых равно count, начиная с индекса index.
  • void Insert(int index, T item) : вставляет элемент item в список по индексу index. Если такого индекса в списке нет, то генерируется исключение
  • void InsertRange(int index, collection) : вставляет коллекцию элементов collection в текущий список начиная с индекса index. Если такого индекса в списке нет, то генерируется исключение
  • bool Remove(T item) : удаляет элемент item из списка, и если удаление прошло успешно, то возвращает true. Если в списке несколько одинаковых элементов, то удаляется только первый из них
  • void RemoveAt(int index) : удаление элемента по указанному индексу index. Если такого индекса в списке нет, то генерируется исключение
  • void RemoveRange(int index, int count) : параметр index задает индекс, с которого надо удалить элементы, а параметр count задает количество удаляемых элементов.
  • int RemoveAll((Predicate match)) : удаляет все элементы, которые соответствуют делегату match. Возвращает количество удаленных элементов
  • void Reverse() : изменяет порядок элементов
  • void Reverse(int index, int count) : изменяет порядок на обратный для элементов, количество которых равно count, начиная с индекса index
  • void Sort() : сортировка списка
  • void Sort(IComparer? comparer) : сортировка списка с помощью объекта comparer, который передается в качестве параметра

Добавление в список

List people = new List () < "Tom" >; people.Add("Bob"); // добавление элемента // people = < "Tom", "Bob" >; people.AddRange(new[] < "Sam", "Alice" >); // добавляем массив // people = < "Tom", "Bob", "Sam", "Alice" >; // также можно было бы добавить другой список // people.AddRange(new List()< "Sam", "Alice" >); people.Insert(0, "Eugene"); // вставляем на первое место // people = < "Eugene", "Tom", "Bob", "Sam", "Alice" >; people.InsertRange(1, new string[] ); // вставляем массив с индекса 1 // people = < "Eugene", "Mike", "Kate", "Tom", "Bob", "Sam", "Alice" >; // также можно было бы добавить другой список // people.InsertRange(1, new List()< "Mike", "Kate" >);

Удаление из списка

var people = new List () < "Eugene", "Mike", "Kate", "Tom", "Bob", "Sam", "Tom", "Alice" >; people.RemoveAt(1); // удаляем второй элемент // people = < "Eugene", "Kate", "Tom", "Bob", "Sam", "Tom", "Alice" >; people.Remove("Tom"); // удаляем элемент "Tom" // people = < "Eugene", "Kate", "Bob", "Sam", "Tom", "Alice" >; // удаляем из списка все элементы, длина строки которых равна 3 people.RemoveAll(person => person.Length == 3); // people = < "Eugene", "Kate", "Alice" >; // удаляем из списка 2 элемента начиная с индекса 1 people.RemoveRange(1, 2); // people = < "Eugene">; // полностью очищаем список people.Clear(); // people = < >;

Поиск и проверка элемента

var people = new List () < "Eugene", "Mike", "Kate", "Tom", "Bob", "Sam" >; var containsBob = people.Contains(«Bob»); // true var containsBill = people.Contains(«Bill»); // false // проверяем, есть ли в списке строки с длиной 3 символа var existsLength3 = people.Exists(p => p.Length == 3); // true // проверяем, есть ли в списке строки с длиной 7 символов var existsLength7 = people.Exists(p => p.Length == 7); // false // получаем первый элемент с длиной в 3 символа var firstWithLength3 = people.Find(p => p.Length == 3); // Tom // получаем последний элемент с длиной в 3 символа var lastWithLength3 = people.FindLast(p => p.Length == 3); // Sam // получаем все элементы с длиной в 3 символа в виде списка List peopleWithLength3 = people.FindAll(p => p.Length == 3); // peopleWithLength3

Получение диапазона и копирование в массив

List people = new List() ; // получаем диапазон со второго по четвертый элемент var range = people.GetRange(1, 3); // range = < "Tom", "Mike", "Sam">; // копируем в массив первые три элемента string[] partOfPeople = new string[3]; people.CopyTo(0, partOfPeople, 0, 3); // partOfPeople = < "Eugene", "Tom", "Mike">;

Расположение элементов в обратном порядке

var people = new List () < "Eugene", "Tom", "Mike", "Sam", "Bob" >; // переворачиваем весь список people.Reverse(); // people = < "Bob","Sam", "Mike", "Tom", "Eugene">; var people2 = new List() < "Eugene", "Tom", "Mike", "Sam", "Bob" >; // переворачиваем часть только 3 элемента с индекса 1 people2.Reverse(1, 3); // people2 = < "Eugene","Sam", "Mike", "Tom", "Bob" >;

Источник

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