System collections generic list

Определение

Добавляет объект в конец очереди List . Adds an object to the end of the List .

Параметры

Объект, добавляемый в конец коллекции List . The object to be added to the end of the List . Для ссылочных типов допускается значение null . The value can be null for reference types.

Реализации

Примеры

Some of the C# examples in this article run in the Try.NET inline code runner and playground. When present, select the Run button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

В следующем примере показано, как добавить, удалить и вставить простой бизнес-объект в List . The following example demonstrates how to add, remove, and insert a simple business object in a List .

В следующем примере показано несколько свойств и методов универсального класса List , включая метод Add. The following example demonstrates several properties and methods of the List generic class, including the Add method. Конструктор без параметров используется для создания списка строк с емкостью 0. The parameterless constructor is used to create a list of strings with a capacity of 0. Отображается свойство Capacity, а затем метод Add используется для добавления нескольких элементов. The Capacity property is displayed, and then the Add method is used to add several items. Элементы перечислены, а свойство Capacity отображается снова вместе со свойством Count, чтобы показать, что емкость увеличилась по мере необходимости. The items are listed, and the Capacity property is displayed again, along with the Count property, to show that the capacity has been increased as needed.

Другие свойства и методы используются для поиска, вставки и удаления элементов из списка и, наконец, для очистки списка. Other properties and methods are used to search for, insert, and remove elements from the list, and finally to clear the list.

Комментарии

List принимает null как допустимое значение для ссылочных типов и допускает дублирование элементов. List accepts null as a valid value for reference types and allows duplicate elements.

Если Count уже равно Capacity, емкость List увеличивается путем автоматического перераспределения внутреннего массива, а существующие элементы копируются в новый массив перед добавлением нового элемента. If Count already equals Capacity, the capacity of the List is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.

Если Count меньше Capacity, этот метод является операцией O (1). If Count is less than Capacity, this method is an O(1) operation. Если емкость необходимо увеличить для размещения нового элемента, этот метод становится операцией O (n), где n — Count. If the capacity needs to be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Type Parameters

The type of elements in the list.

Examples

The following example demonstrates how to add, remove, and insert a simple business object in a List .

The following example demonstrates several properties and methods of the List generic class of type string. (For an example of a List of complex types, see the Contains method.)

The parameterless constructor is used to create a list of strings with the default capacity. The Capacity property is displayed and then the Add method is used to add several items. The items are listed, and the Capacity property is displayed again, along with the Count property, to show that the capacity has been increased as needed.

The Contains method is used to test for the presence of an item in the list, the Insert method is used to insert a new item in the middle of the list, and the contents of the list are displayed again.

The default Item[Int32] property (the indexer in C#) is used to retrieve an item, the Remove method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The Remove method always removes the first instance it encounters.

The TrimExcess method is used to reduce the capacity to match the count, and the Capacity and Count properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized.

Finally, the Clear method is used to remove all items from the list, and the Capacity and Count properties are displayed.

Remarks

The List class is the generic equivalent of the ArrayList class. It implements the IList generic interface by using an array whose size is dynamically increased as required.

Читайте также:  Fec что это такое

You can add items to a List by using the Add or AddRange methods.

The List class uses both an equality comparer and an ordering comparer.

Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equality comparer for the list elements. The default equality comparer for type T is determined as follows. If type T implements the IEquatable generic interface, then the equality comparer is the Equals(T) method of that interface; otherwise, the default equality comparer is Object.Equals(Object).

Methods such as BinarySearch and Sort use an ordering comparer for the list elements. The default comparer for type T is determined as follows. If type T implements the IComparable generic interface, then the default comparer is the CompareTo(T) method of that interface; otherwise, if type T implements the nongeneric IComparable interface, then the default comparer is the CompareTo(Object) method of that interface. If type T implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly.

The List is not guaranteed to be sorted. You must sort the List before performing operations (such as BinarySearch) that require the List to be sorted.

Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

.NET Framework only: For very large List objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

List accepts null as a valid value for reference types and allows duplicate elements.

For an immutable version of the List class, see ImmutableList .

Performance Considerations

In deciding whether to use the List or ArrayList class, both of which have similar functionality, remember that the List class performs better in most cases and is type safe. If a reference type is used for type T of the List class, the behavior of the two classes is identical. However, if a value type is used for type T , you need to consider implementation and boxing issues.

If a value type is used for type T , the compiler generates an implementation of the List class specifically for that value type. That means a list element of a List object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation.

Make certain the value type used for type T implements the IEquatable generic interface. If not, methods such as Contains must call the Object.Equals(Object) method, which boxes the affected list element. If the value type implements the IComparable interface and you own the source code, also implement the IComparable generic interface to prevent the BinarySearch and Sort methods from boxing list elements. If you do not own the source code, pass an IComparer object to the BinarySearch and Sort methods

It is to your advantage to use the type-specific implementation of the List class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. The reason is your implementation must do what the .NET Framework does for you already, and the common language runtime can share Microsoft intermediate language code and metadata, which your implementation cannot.

F# Considerations

The List class is used infrequently in F# code. Instead, Lists, which are immutable, singly-linked lists, are typically preferred. An F# List provides an ordered, immutable series of values, and is supported for use in functional-style development. When used from F#, the List class is typically referred to by the ResizeArray type abbreviation to avoid naming conflicts with F# Lists

Constructors

Initializes a new instance of the List class that is empty and has the default initial capacity.

Initializes a new instance of the List class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

Initializes a new instance of the List class that is empty and has the specified initial capacity.

Properties

Gets or sets the total number of elements the internal data structure can hold without resizing.

Gets the number of elements contained in the List .

Gets or sets the element at the specified index.

Methods

Adds an object to the end of the List .

Adds the elements of the specified collection to the end of the List .

Returns a read-only ReadOnlyCollection wrapper for the current collection.

Searches a range of elements in the sorted List for an element using the specified comparer and returns the zero-based index of the element.

Searches the entire sorted List for an element using the default comparer and returns the zero-based index of the element.

Searches the entire sorted List for an element using the specified comparer and returns the zero-based index of the element.

Читайте также:  Shiny lux таблетки для посудомоечных машин отзывы

Removes all elements from the List .

Determines whether an element is in the List .

Converts the elements in the current List to another type, and returns a list containing the converted elements.

Copies a range of elements from the List to a compatible one-dimensional array, starting at the specified index of the target array.

Copies the entire List to a compatible one-dimensional array, starting at the beginning of the target array.

Copies the entire List to a compatible one-dimensional array, starting at the specified index of the target array.

Determines whether the specified object is equal to the current object.

(Inherited from Object)

Exists(Predicate )

Determines whether the List contains elements that match the conditions defined by the specified predicate.

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List .

Retrieves all the elements that match the conditions defined by the specified predicate.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List that starts at the specified index and contains the specified number of elements.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List that extends from the specified index to the last element.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire List .

Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire List .

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List that contains the specified number of elements and ends at the specified index.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the List that extends from the first element to the specified index.

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire List .

Performs the specified action on each element of the List .

Returns an enumerator that iterates through the List .

Serves as the default hash function.

(Inherited from Object)

GetRange(Int32, Int32)

Creates a shallow copy of a range of elements in the source List .

Gets the Type of the current instance.

(Inherited from Object)

IndexOf(T)

Searches for the specified object and returns the zero-based index of the first occurrence within the entire List .

Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List that extends from the specified index to the last element.

Searches for the specified object and returns the zero-based index of the first occurrence within the range of elements in the List that starts at the specified index and contains the specified number of elements.

Inserts an element into the List at the specified index.

Inserts the elements of a collection into the List at the specified index.

Searches for the specified object and returns the zero-based index of the last occurrence within the entire List .

Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the List that extends from the first element to the specified index.

Searches for the specified object and returns the zero-based index of the last occurrence within the range of elements in the List that contains the specified number of elements and ends at the specified index.

Creates a shallow copy of the current Object.

(Inherited from Object)

Remove(T)

Removes the first occurrence of a specific object from the List .

Removes all the elements that match the conditions defined by the specified predicate.

Removes the element at the specified index of the List .

Removes a range of elements from the List .

Reverses the order of the elements in the entire List .

Reverses the order of the elements in the specified range.

Sorts the elements in the entire List using the default comparer.

Sorts the elements in the entire List using the specified Comparison .

Sorts the elements in the entire List using the specified comparer.

Sorts the elements in a range of elements in List using the specified comparer.

Copies the elements of the List to a new array.

Returns a string that represents the current object.

(Inherited from Object)

Читайте также:  Sata raid драйвер для amd windows 7
TrimExcess()

Sets the capacity to the actual number of elements in the List , if that number is less than a threshold value.

Determines whether every element in the List matches the conditions defined by the specified predicate.

Explicit Interface Implementations

Copies the elements of the ICollection to an Array, starting at a particular Array index.

Gets a value indicating whether access to the ICollection is synchronized (thread safe).

Gets an object that can be used to synchronize access to the ICollection.

Gets a value indicating whether the ICollection is read-only.

Returns an enumerator that iterates through a collection.

Returns an enumerator that iterates through a collection.

Adds an item to the IList.

Determines whether the IList contains a specific value.

Determines the index of a specific item in the IList.

Inserts an item to the IList at the specified index.

Gets a value indicating whether the IList has a fixed size.

Gets a value indicating whether the IList is read-only.

Gets or sets the element at the specified index.

Removes the first occurrence of a specific object from the IList.

Extension Methods

Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable object where the generic parameter T is DataRow.

Copies DataRow objects to the specified DataTable, given an input IEnumerable object where the generic parameter T is DataRow.

Copies DataRow objects to the specified DataTable, given an input IEnumerable object where the generic parameter T is DataRow.

Casts the elements of an IEnumerable to the specified type.

Filters the elements of an IEnumerable based on a specified type.

Enables parallelization of a query.

Returns a collection of elements that contains the ancestors of every node in the source collection.

Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Only elements that have a matching XName are included in the collection.

Returns a collection of the descendant nodes of every document and element in the source collection.

Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

Returns a collection of the child elements of every element and document in the source collection.

Returns a filtered collection of the child elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Returns a collection of the child nodes of every document and element in the source collection.

Removes every node in the source collection from its parent node.

Applies to

Thread Safety

Public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Платформа .NET содержит набор типов для хранения и управления коллекциями объектов: списки с изменяемыми размерами, связанные списки, отсортированные и неотсортированные словари, массивы.

Типы в .NET для коллекций можно разделить на три категории:

  • интерфейсы, определяющие стандартные протоколы коллекций
  • готовые к использованию классы коллекций (списки, словари)
  • базовые классы для написания коллекций

Все эти типы расположены в следующих пространствах имен:

  • System.Collections — необобщенные классы и интерфейсы коллкций
  • System.Collections.Specialized — строго типизированные необобщенные классы коллекций
  • System.Collections.Generic — обобщенные классы и интерфейсы коллекций
  • System.Collections.ObjectModel — прокси и базовые классы для специальных коллекций
  • System.Collections.Concurrent — коллекции, безопасные к потокам

Все коллекции являются перечислениями и реализуют (должны реализовывать) интерфейс IEnumerable или IEnumerable .

Интерфейсы перечислений обеспечивают протокол для итерации по коллекции, но не предоставляют механизма для определения размера коллекции, доступа к члену по индексу, поиска или модификации коллекции. Для данного функционала определены интерфейсы ICollection , IList и IDictionary . Каждый из них имеет обобщенную и необобщенную версию (однако необобщенные используются редко).

Иерархия интерфейсов коллекций:

  • IEnumerable и IEnumerable — минимальный уровень функциональности: только перечисление
  • ICollection и ICollection — средний уровень функциональности, например, свойство Count
  • IList , IDictionary и их необобщенные аналоги — максимальный уровень функциональности

Перечисление (Enumeration)

Нумератор, или перечислитель (enumerator) — доступный только для чтения однонаправленный курсор (forward-only cursor — курсор, движущийся только вперёд, без возможности обратного перемещения) перебирающий последовательность (sequence) значений. Нумератор представляет собой объект, реализующий интерфейс System.Collections.IEnumerator или System.Collections.Generic.IEnumerator .

Инструкция foreach перебирает, или выполняет итерацию (iterate) над перечислимыми (enumerable) объектами. Перечислимые объекты — это логическое представление последовательностей. Перечислимый объект — это не курсор, о котором говорилось выше, а объект, содержащий такой курсор, способный перемещаться по объекту и перебирать его. Перечислимый объект либо реализует интерфейс IEnumerable или IEnumer able , либо содержит метод GetEnumerator , который возвращает нумератор (enumerator).

Интерфейсы IEnumerable и IEnumerator

Интерфейс IEnumerator определяет базовый низкоуровневый протокол, посредством которого производится проход по элементам (перечисление) последовательности в одонаправленной манере. Объявление этого интерфейса:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock detector