Collections 6 2 2

broken image


-->

For many applications, you want to create and manage groups of related objects. There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.

Arrays are most useful for creating and working with a fixed number of strongly typed objects. For information about arrays, see Arrays.

Sep 01, 2021 The deque after deleting from right is: deque(6, 1, 2, 3) The deque after deleting from left is: deque(1, 2, 3) Note: For more information, refer Deque in Python. UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary. The best 6 bedroom house floor plans & designs. Find large, luxury, mansion, family, duplex, 2 story & more blueprints. Call 1-800-913-2350 for expert help. See full list on docs.microsoft.com.

Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

A collection is a class, so you must declare an instance of the class before you can add elements to that collection.

If your collection contains elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. A generic collection enforces type safety so that no other data type can be added to it. When you retrieve an element from a generic collection, you do not have to determine its data type or convert it.

Note

For the examples in this topic, include using directives for the System.Collections.Generic and System.Linq namespaces.

Iclipboard 6 0 0 – a flexible clipboard manager. In this topic

Using a Simple Collection

The examples in this section use the generic List class, which enables you to work with a strongly typed list of objects.

The following example creates a list of strings and then iterates through the strings by using a foreach statement.

Collections 6 2 2

If the contents of a collection are known in advance, you can use a collection initializer to initialize the collection. For more information, see Object and Collection Initializers.

The following example is the same as the previous example, except a collection initializer is used to add elements to the collection.

You can use a for statement instead of a foreach statement to iterate through a collection. You accomplish this by accessing the collection elements by the index position. The index of the elements starts at 0 and ends at the element count minus 1.

The following example iterates through the elements of a collection by using for instead of foreach.

The following example removes an element from the collection by specifying the object to remove.

The following example removes elements from a generic list. Instead of a foreach statement, a for statement that iterates in descending order is used. This is because the RemoveAt method causes elements after a removed element to have a lower index value.

For the type of elements in the List, you can also define your own class. In the following example, the Galaxy class that is used by the List is defined in the code.

Kinds of Collections

Many common collections are provided by .NET. Each type of collection is designed for a specific purpose.

Some of the common collection classes are described in this section:

  • System.Collections.Generic classes

  • System.Collections.Concurrent classes

  • System.Collections classes

System.Collections.Generic Classes

You can create a generic collection by using one of the classes in the System.Collections.Generic namespace. A generic collection is useful when every item in the collection has the same data type. A generic collection enforces strong typing by allowing only the desired data type to be added.

The following table lists some of the frequently used classes of the System.Collections.Generic namespace:

ClassDescription
DictionaryRepresents a collection of key/value pairs that are organized based on the key.
ListRepresents a list of objects that can be accessed by index. Provides methods to search, sort, and modify lists.
QueueRepresents a first in, first out (FIFO) collection of objects.
SortedListRepresents a collection of key/value pairs that are sorted by key based on the associated IComparer implementation.
StackRepresents a last in, first out (LIFO) collection of objects.

For additional information, see Commonly Used Collection Types, Selecting a Collection Class, and System.Collections.Generic.

System.Collections.Concurrent Classes

In .NET Framework 4 and later versions, the collections in the System.Collections.Concurrent namespace provide efficient thread-safe operations for accessing collection items from multiple threads.

The classes in the System.Collections.Concurrent namespace should be used instead of the corresponding types in the System.Collections.Generic and System.Collections namespaces whenever multiple threads are accessing the collection concurrently. For more information, see Thread-Safe Collections and System.Collections.Concurrent.

Some classes included in the System.Collections.Concurrent namespace are BlockingCollection, ConcurrentDictionary, ConcurrentQueue, and ConcurrentStack.

System.Collections Classes

The classes in the System.Collections namespace do not store elements as specifically typed objects, but as objects of type Object.

Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of the legacy types in the System.Collections namespace.

The following table lists some of the frequently used classes in the System.Collections namespace:

ClassDescription
ArrayListRepresents an array of objects whose size is dynamically increased as required.
HashtableRepresents a collection of key/value pairs that are organized based on the hash code of the key.
QueueRepresents a first in, first out (FIFO) collection of objects.
StackRepresents a last in, first out (LIFO) collection of objects.

The System.Collections.Specialized namespace provides specialized and strongly typed collection classes, such as string-only collections and linked-list and hybrid dictionaries.

Object And Collection Initializers

Implementing a Collection of Key/Value Pairs

The Dictionary generic collection enables you to access to elements in a collection by using the key of each element. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is fast because the Dictionary class is implemented as a hash table.

The following example creates a Dictionary collection and iterates through the dictionary by using a foreach statement.

To instead use a collection initializer to build the Dictionary collection, you can replace the BuildDictionary and AddToDictionary methods with the following method.

The following example uses the ContainsKey method and the Item[] property of Dictionary to quickly find an item by key. The Item property enables you to access an item in the elements collection by using the elements[symbol] in C#.

The following example instead uses the TryGetValue method quickly find an item by key.

Using LINQ to Access a Collection

LINQ (Language-Integrated Query) can be used to access collections. LINQ queries provide filtering, ordering, and grouping capabilities. For more information, see Getting Started with LINQ in C#.

The following example runs a LINQ query against a generic List. The LINQ query returns a different collection that contains the results.

Sorting a Collection

The following example illustrates a procedure for sorting a collection. The example sorts instances of the Car class that are stored in a List. The Car class implements the IComparable interface, which requires that the CompareTo method be implemented.

Each call to the CompareTo method makes a single comparison that is used for sorting. User-written code in the CompareTo method returns a value for each comparison of the current object with another object. The value returned is less than zero if the current object is less than the other object, greater than zero if the current object is greater than the other object, and zero if they are equal. This enables you to define in code the criteria for greater than, less than, and equal.

In the ListCars method, the cars.Sort() statement sorts the list. This call to the Sort method of the List causes the CompareTo method to be called automatically for the Car objects in the List.

Defining a Custom Collection

You can define a collection by implementing the IEnumerable or IEnumerable interface.

Although you can define a custom collection, it is usually better to instead use the collections that are included in .NET, which are described in Kinds of Collections earlier in this article.

The following example defines a custom collection class named AllColors. This class implements the IEnumerable interface, which requires that the GetEnumerator method be implemented.

See Full List On Docs.microsoft.com

The GetEnumerator method returns an instance of the ColorEnumerator class. ColorEnumerator implements the IEnumerator interface, which requires that the Current property, MoveNext method, and Reset method be implemented.

Iterators

An iterator is used to perform a custom iteration over a collection. An iterator can be a method or a get accessor. An iterator uses a yield return statement to return each element of the collection one at a time.

You call an iterator by using a foreach statement. Each iteration of the foreach loop calls the iterator. When a yield return statement is reached in the iterator, an expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator is called.

For more information, see Iterators (C#).

Collections 6 2 2 6

The following example uses an iterator method. The iterator method has a yield return statement that is inside a for loop. In the ListEvenNumbers method, each iteration of the foreach statement body creates a call to the iterator method, which proceeds to the next yield return statement.

See also





broken image