logo
CSharp_Prog_Guide

Коллекции и структуры данных

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

Для управления коллекцией используйте класс Array и классы из пространства имен System.Collections для добавления, удаления и изменения либо отдельных элементов коллекции, либо диапазона элементов. Коллекцию можно скопировать целиком в другую коллекцию.

Некоторые классы коллекций предоставляют возможность сортировки, и большинство из них индексированы. Управление памятью осуществляется автоматически, а вместимость коллекции увеличивается по мере необходимости. Синхронизация обеспечивает потокобезопасность при доступе к членам коллекции. Некоторые классы коллекций могут создавать оболочки, поодерживающие фиксированный размер коллекции или ограничение доступа к членам коллекции только чтением. Любой класс коллекций может создать свой собственный нумератор, облегчающий выполнение итерации элементов.

В .NET Framework, версия 2.0 классы универсальных коллекций предоставляют новые функциональные возможности и облегчают создание строго типизированных коллекций. Обратитесь к описанию пространств имен System.Collections.Generic и System.Collections.ObjectModel.

Функция LINQ to Objects позволяет использовать LINQ запросы для доступа к объектам в памяти, если объект типа реализовывает IEnumerable или IEnumerable<(Of <(T>)>). LINQ запросы предоставляют общий шаблон для доступа к данным, являются более четкими и удобочитаемыми, чем стандартные циклы foreach, а также предоставляют возможности фильтрации, сортировки и группировки. LINQ запросы также могут повысить производительность.

Defining Collections

A collection is a set of similarly typed objects that are grouped together.

Objects of any type can be grouped into a single collection of the type Object to take advantage of constructs that are inherent in the language. For example, the C# foreach statement (for each in Visual Basic) expects all objects in the collection to be of a single type.

However, in a collection of type Object, additional processing is done on the elements individually, such as boxing and unboxing or conversions, which affect the performance of the collection. Boxing and unboxing typically occur if storing or retrieving a value type in a collection of type Object.

Generic collections, such as List<(Of <(T>)>), and strongly typed nongeneric collections, such as StringCollection, avoid these performance hits if the type of the element is the type that the collection is intended for (for example, storing or retrieving strings from a StringCollection). In addition, strongly typed collections automatically perform type validation of each element added to the collection.

All collections that directly or indirectly implement the ICollection interface or the ICollection<(Of <(T>)>) generic interface share several features in addition to methods that add, remove, or search elements:

An enumerator is an object that iterates through its associated collection. It can be thought of as a movable pointer to any element in the collection. An enumerator can be associated with only one collection, but a collection can have multiple enumerators. The C# foreach statement (for each in Visual Basic) uses the enumerator and hides the complexity of manipulating the enumerator.

Synchronization provides thread safety when accessing elements of the collection. The collections are not thread safe by default. Only a few classes in the System.Collections namespaces provide a Synchronize method that creates a thread-safe wrapper over the collection. However, all classes in all System.Collections namespaces provide a SyncRoot property that can be used by derived classes to create their own thread-safe wrapper. An IsSynchronized property is also provided to determine whether the collection is thread safe. Synchronization is not available in the ICollection<(Of <(T>)>) generic interface.

All collections can be copied to an array using the CopyTo method; however, the order of the elements in the new array is based on the sequence in which the enumerator returns them. The resulting array is always one-dimensional with a lower bound of zero.

Note that the ICollection<(Of <(T>)>) generic interface has additional members, which the nongeneric interface does not include.