C # Collection types

Source: Internet
Author: User

C # Collective type (collections in C #)

Collections are an important part of the. NET FCL (Framework Class Library) and one of the most commonly used features in our development, almost everywhere. As the saying goes, know its why, usually see ienumerable,ienumerator,icollection do not know their respective differences? What other collection classes have you used besides list and dictionary? Cut the crap, we'll see some of these today. Defines the interface of the collection class and their implementation.

    • Collection interface
    • Associative generic collection classes
    • Non-associative generic collection classes
    • Recommended Use Scenarios
    • Non-generic collection classes
    • Thread-Safe Collection classes
Collection interface

Let's take a look at what interfaces the FCL provides for us:

  

IEnumerable and Ienumberator
1234567 public  interface  ienumerator {        bool  movenext ();      object  current {   get ;}      void  reset ();

IEnumerator defines the basic way we iterate through the collection so that we can implement one-way forward access to each element in the collection. And IEnumerable has only one method GetEnumerator that is to get the walker.

1234 publicinterfaceIEnumerable{    IEnumerator GetEnumerator();}

Note: The foreach we often use is a syntactic sugar that actually invokes the traversal function implemented by current and MoveNext inside enumerator.

123456789101112131415161718192021 List<string> list = newList<string>(){    "Jesse",    "Chloe",    "Lei",    "Jim",    "XiaoJun"};// Iterate the list by using foreachforeach(varbuddy inlist){    Console.WriteLine(buddy);} // Iterate the list by using enumeratorList<string>.Enumerator enumerator = list.GetEnumerator();while(enumerator.MoveNext()){    Console.WriteLine(enumerator.Current);}

The above code uses the foreach and enumerator-to-il to be translated into enumerator MoveNext and current at the end.

IEnumerable is a very useful interface and the benefits of implementing it include:

    1. Support for foreach statements
    2. Interacting with other class libraries as a standard collection class
    3. Meet the requirements of a more complex collection interface
    4. Support for collection initializers

Of course there are many ways to implement it, as follows:

    1. If our collection comes from encapsulating other collection classes, then we can return directly to the enumerator of this collection
    2. Return by yield return
    3. Implement our own IEnumerator to achieve

Here is a demonstration of how yield can be implemented to return enumerator

12345678910111213141516171819202122232425 publicclassBuddyList : IEnumerable{    privatestring[] data= newstring[]    {        "Jesse",        "Chloe",        "Lei",        "Jim",        "XiaoJun"    };    publicIEnumerator GetEnumerator()    {        foreach(varstr indata)        {            yieldreturnstr;        }    }}var myBuddies= newBuddyList();foreach(varstr inmyBuddies){    Console.WriteLine(str);}

  

Icollection<t> and ICollection

From the top of the first picture we can know that ICollection is directly inherited from IEnumerable. In fact, we can say that ICollection supports some features more than IEnumerable, and not only provides basic traversal functionality, but also includes:

    1. Statistics set and number of elements
    2. Get the subscript of an element
    3. Determine if there is
    4. Add an element to the end
    5. Remove elements, etc...

ICollection is slightly different from icollection<t>, ICollection does not provide the ability to edit collections, that is, add and remove. This includes checking whether an element exists contains or not.

Ilist<t> and IList

IList is directly inherited from ICollection and IEnumerable. So it includes the functionality of both, and supports accessing and adding elements based on subscripts. IndexOf, Insert, RemoveAt and so on. We can say that IEnumerable supports the least functionality, only traversal. The ICollection supports a bit more features, not only traversal but also the ability to maintain the set. And IList is the most complete version.

Ireadonlylist<t>

This is the new interface type in Framework4.5, which can be seen as a reduced version of ilist<t>, removing all the functionality that could change this collection. For example: ADD, RemoveAt and so on.

Idictionary<tkey,tvalue>

IDictionary provides access to the set of key-value pairs, and also inherits Icollection<t> and IEnumerable, extending the means to access and manipulate data through key.

Associative generic collection classes

The Associative collection class, which we often call a set of key-value pairs, allows us to access and maintain the collection through key. Let's start by looking at what generic associative collection classes The FCL provides for us:

    1. Dictionary<tkey,tvalue>
    2. Sorteddictionary<tkey,tvalue>
    3. Sortedlist<tkey,tvalue>
Dictionary<tkey,tvalue>

Dictionary<tkey,tvalue> may be our most commonly used association, its access, addition, the time it takes to delete data is the fastest in all collection classes, because it internally uses Hashtable as the storage structure, so no matter how many key-value pairs are stored , the time spent in query/Add/delete is the same, and its time complexity is O (1).

Dictionary<tkey,tvalue> Advantage is to find the insertion speed fast, then what is its disadvantage? Because using Hashtable as a storage structure means that the data inside is unordered, so it takes a little effort to traverse the data in dictionary<tkey,tvalue> in a certain order.

The type of TKey must implement GetHashCode () and Equals () or provide a iequalitycomparer, Otherwise, the operation may cause problems.

Sorteddictioanry<tkey,tvalue>

Sorteddictionary<tkey,tvalue> and dictionary<tkey,tvalue> are roughly similar, but there is a little bit of a difference in how they are implemented. Sorteddictionary<tkey,tvalue> uses a binary tree as the storage structure. and are listed in the order of key. Then the sorteddictionary<tkey,tvalue> TKey must realize icomparable<tkey>. if you want to quickly query the same time and good support for sorting, then use SortedDictionary bar.

Sortedlist<tkey,tvalue>

Sortedlist<tkey,tvalue> is another associative collection that supports sorting. But the difference is that SortedList actually stores the data in the array. This means that both the add and remove operations are linear and the time complexity is O (n), because the elements that manipulate them can cause all data movement. But because of the two-point search when searching, the performance of the lookup is better, and the time complexity is O (log n). So the recommended scenario is this: if you want to find it quickly, and you want the collection to be in the order of key, the last set of operations (add and remove) less, is SortedList.

Non-associative generic collection classes

A non-associative set is a collection class that does not operate with a key, and usually we can use the element itself or subscript to manipulate it. The FCL mainly provides us with the following types of non-associative generic collection classes.

    1. List<t>
    2. Linkedlist<t>
    3. Hashset<t>
    4. Sortedset<t>
    5. Stack<t>
    6. Queue<t>
List<t>

The generic list class provides a collection type of unlimited length, the list maintains an array of length internally (the default initial length is 4), and when we insert an element whose length exceeds 4 or the initial length, it will recreate a new array, the length of which is twice times the initial length (not always twice times, When the discovery continues to expand, the multiples become larger), and the original array is copied over. So if you know how many elements we are going to use with this collection, we can specify the initial value at the time of creation, thus avoiding the repetition of creating new arrays and copying values.

In addition, because the inner essence is an array, it is faster to add data in the list, but it is relatively inefficient to add the deleted data in the header or the middle of the data because it affects the rearrangement of other data.

Linkedlist<t>

LinkedList maintains a two-way linked list internally, which means that we add or delete data anywhere in the LinkedList, and its performance is fast. Because it does not cause other elements to move. In general, the list is enough for us to use, but it is recommended to use LinkedList if the add-delete operation is very frequent in the middle of the collection.

Hashset<t>

HashSet is an unordered collection that keeps the uniqueness. We can also think of HashSet as Dictionary<tkey,tvalue>, except that TKey and TValue all point to the same object. HashSet is perfect for when we need to keep elements unique within the collection but do not need to be ordered in order.

HashSet does not support subscript access.

Sortedset<t>

SortedSet and HashSet, just like SortedDictionary and dictionary, do you remember the difference between the two? The interior of the SortedSet is also a binary tree, used to support sequential permutation elements.

Stack<t>

Last-in-first-out queue
Access by subscript is not supported

Queu<t>

FIFO-first-out queue
Access by subscript is not supported

Recommended Use Scenarios

Collection

Sequential arrangement

Even-shun storage

Direct access Mode

Access time

Operating time

Note

Dictionary

Is

Key

Key:

O (1)

O (1)

Fastest access performance, no sorting support

Sorteddinctionary

Sequential arrangement

Whether

Key

Key:
O (log n)

O (log n)

Quick access and support for sorting tradeoffs

SortedList

Sequential arrangement

Is

Key

Key:

O (log n)

O (N)

Similar to SortedDictionary, only the internal data substitution tree as the storage structure.

List

The user can precisely control the position of the element

Is

Index

Index:o (1)

Value:o (N)

O (N)

Most suitable for a small collection that requires direct access to each element.

LinkedList

The user can precisely control the position of the element

Whether

Not supported

Value:

O (N)

O (1)

It is best suited to not having to directly access a single element, but to add/remove very frequent scenes in the collection.

HashSet

Not supported

Is

Key

Key:

O (1)

O (1)

A collection of elements that can maintain uniqueness. Sorting is not supported

SortedSet

Sequential arrangement

Whether

Key

Key:

O (log n)

O (log n)

can maintain element uniqueness and support sorting.

Stack

Lifo

Is

Only the top element can be obtained

Top:o (1)

O (1)

Queue

Fifo

Is

Only the bottom element can be obtained

Front:o (1)

O (1)

Non-generic class collection

The generic collection class is in the. NET2.0 out of the time, that is, in the 1.0 is not so convenient things. Now basically we're not using these collection classes, unless we're doing some work that is compatible with the old code. Take a look at the collection classes that the 1.0-era. NET programmers can use.

    1. Arrarylist

Later replaced by List<t>.

    1. HashTable was later replaced by Dictionary<tkey,tvalue>.
    2. The Queue was later replaced by Queue<t>.
    3. SortedList was later replaced by Sortedlist<t>.
    4. The Stack was later replaced by Stack<t>.
Thread-Safe Collection classes
    1. Concurrentqueue thread-safe version of the queue
    2. Concurrentstack thread-safe version of the stack
    3. Concurrentbag Thread-Safe collection of objects
    4. Concurrentdictionary Thread-Safe dictionary
    5. BlockingCollection

. NET provides us with the collection class is one of our very common tool classes, I hope this article can help you better understand these collection classes. Of course, there are imperfections in the personal sense, such as Hashtable and binary Search tree, which are not scrutiny, including the comparison between the unidirectional list and the doubly linked list, which is not mentioned here. Interested friends can take a closer look.

C # Collection types

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.