C # large inventory of Collection types,

Source: Internet
Author: User

[Switch] C # large inventory of Collection types,

C # collective type (Collections in C #)

Collections are an important part of. net fcl (Framework Class Library). They are also one of the most commonly used features in our development and are almost ubiquitous. As the saying goes, do you know why? Do you know the differences between IEnumerable, IEnumerator, and ICollection? In addition to List and Dictionary, what other collection classes have you used? Today, let's look at some of the interfaces that define collection classes and their implementations.

  • Set Interface
  • Correlated generic collection class
  • Non-correlated generic collection class
  • Recommended use cases
  • Non-generic collection class
  • Thread security collection class
Set Interface

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

  

IEnumerable and IEnumberator
public interface IEnumerator{    bool MoveNext();    object Current {  get; }    void Reset();}

IEnumerator defines the basic method for traversing the set so that we can access every element in the set one way forward. IEnumerable only has one GetEnumerator method to get the traversal tool.

public interface IEnumerable{    IEnumerator GetEnumerator();}

Note:We often use foreach as a syntactic sugar. In fact, we still call the traversal functions implemented by Current and MoveNext in Enumerator.

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

The foreach and enumerator used in the above Code are finally translated into MoveNext and Current of enumerator.

IEnumerable is a useful interface. Its advantages include:

Of course, there are also many implementation methods, as shown below:

Here we will show you how to use yield to return enumerator

public class BuddyList : IEnumerable{    private string[] data= new string[]    {         "Jesse",        "Chloe",        "Lei",        "Jim",        "XiaoJun"    };    public IEnumerator GetEnumerator()    {        foreach (var str in data)        {            yield return str;        }    }}var myBuddies= new BuddyList();foreach (var str in myBuddies){    Console.WriteLine(str);}

  

ICollection <T> and ICollection

From the first figure above, we can know that ICollection is directly inherited from IEnumerable. In fact, ICollection supports more functions than IEnumerable, not only providing basic traversal functions, but also including:

ICollection and ICollection <T> are slightly different. ICollection does not provide the function of editing a set, that is, Add and Remove. Including checking whether the element has Contains is not supported.

IList <T> and IList

IList is directly inherited from ICollection and IEnumerable. Therefore, it includes both functions and supports accessing and adding elements based on subscripts. IndexOf, Insert, RemoveAt, and so on. We can say that IEnumerable supports the least functions, only traversal. ICollection supports a little more features, not only traversing but also maintaining this set. IList is the most comprehensive version.

IReadOnlyList <T>

This is the newly added interface type in Framework4.5. It can be considered as the reduced version of IList <T>, removing all functions that may change this set. For example, Add or RemoveAt.

IDictionary <TKey, TValue>

IDictionary provides access to the set of Key-value pairs, inherits ICollection <T> and IEnumerable, and extends the methods for accessing and operating data through keys.

Correlated generic collection class

The Correlated set class is the set of Key-value pairs that we often call. It allows us to access and maintain the set through the Key. Let's take a look at the generic relevance set classes that FCL provides for us:

Dictionary <TKey, TValue>

Dictionary <TKey, TValue> may be the most common set of associativity. It takes the fastest time to access, add, and delete data in all collection classes, because it uses Hashtable as the storage structure, no matter how many key-value pairs are stored, the query, add, or delete operations take the same time, its time complexity is O (1 ).

Dictionary <TKey, TValue> has the advantage of fast query and insertion speed. What is its disadvantage? Because Hashtable is used as the storage structure, it means that the data in it is unordered, so we want to traverse the Dictionary in a certain order <TKey, the data in TValue> takes a little time.

The TKey type must be implemented.GetHashCode ()AndEquals () Or provideIEqualityComparer,Otherwise, problems may occur.

SortedDictioanry <TKey, TValue>

SortedDictionary <TKey, TValue> and Dictionary <TKey, TValue> are similar in general, but there are some differences in implementation methods. SortedDictionary <TKey, TValue> uses a binary tree as the storage structure. In the order of keys. In this case, the TKey of SortedDictionary <TKey, TValue> must be implemented.IComparable <TKey>.If you want to quickly query and support sorting, use SortedDictionary.

SortedList <TKey, TValue>

SortedList <TKey, TValue> is another set of associations that support sorting. However, the difference is that SortedList stores data in arrays. That is to say, the add and remove operations are linear, and the time complexity is O (n), because the elements in the operations may cause all data to move. However, because binary search is used during search, the search performance is better, and the time complexity is O (log n ). Therefore, we recommend that you use the following scenario: If you want to quickly search for a set and sort the set in the order of keys, the last set has fewer operations (add and remove, it is SortedList.

Non-correlated generic collection class

A non-correlated set is a collection class that does not require key operations. Generally, we can operate it with elements or subscripts. FCL mainly provides the following non-correlated generic collection classes.

List <T>

The generic List class provides a set type with no limit on the length. The List maintains an array of a certain length internally (the default initial length is 4 ), when the length of the inserted element exceeds 4 or the initial length, a new array is created, the length of the new array is twice the initial length (not always twice. When we find that we are constantly expanding, the multiples will increase), and then copy the original array. Therefore, if we know how many elements will be loaded using this set, we can specify the initial value during creation to avoid repeated creation of new arrays and copying values.

In addition, because the internal is actually an array, It is faster to add data to the List, however, adding or deleting data in the data header or in the middle is more inefficient because it will affect the re-arrangement of other data.

Revoke list <T>

The consumer list maintains a two-way linked list internally, which means that the performance of adding or deleting data anywhere in the consumer list is fast. Because it will not lead to the movement of other elements. In general, the List is enough for our use. However, if you frequently add or delete the set in the middle, we recommend that you use the sort List.

HashSet <T>

HashSet is an unordered set that can be unique. We can also regard HashSet as a Dictionary <TKey, TValue>, except that both TKey and TValue point to the same object. HashSet is very suitable when we need to keep the element uniqueness in the set but do not need to be arranged in order.

HashSet does not support subscript access.

SortedSet <T>

SortedSet and HashSet are the same as SortedDictionary and Dictionary. Do you still remember the differences between them? SortedSet is also a binary tree that supports ordered elements.

Stack <T>

Back-to-first-out queue
Access by subscript is not supported

Queu <T>

FIFO queue
Access by subscript is not supported

Recommended use cases

 

Set

Sequential arrangement

Continuous Storage

Direct Access

Access time

Operation Time

Remarks

Dictionary

 

Yes

Key

Key:

O (1)

 

O (1)

The fastest access performance does not support sorting

SortedDinctionary

Sequential arrangement

No

Key

Key:
O (log n)

O (log n)

Compromise between quick access and support for sorting

SortedList

Sequential arrangement

Yes

Key

Key:

O (log n)

 

O (n)

Similar to SortedDictionary, the data substitution tree is used internally as the storage structure.

List

Users can precisely control the position of elements.

Yes

Index

Index: O (1)

Value: O (n)

 

O (n)

It is most suitable for accessing a small set of each element directly.

Shortlist

Users can precisely control the position of elements.

No

Not Supported

Value:

O (n)

 

O (1)

It is most suitable for scenarios where you do not need to directly access a single element, but Add/Remove frequently in the set.

HashSet

Not Supported

Yes

Key

Key:

O (1)

 

O (1)

A set of unique elements. Sorting is not supported.

SortedSet

Sequential arrangement

No

Key

Key:

O (log n)

 

O (log n)

It can maintain element uniqueness and support sorting.

Stack

LIFO

Yes

Only top elements can be obtained.

Top: O (1)

O (1)

 

Queue

FIFO

Yes

Only the bottom element can be obtained.

Front: O (1)

O (1)

 

Non-generic class set

Generic collection classes come out at. NET2.0, which means there is no such convenient thing at 1.0. Now we basically do not use these collection classes unless we are doing some work that is compatible with the old code. Let's take a look at the collection classes available to. NET programmers in the 1.0 age.

It was later replaced by List <T>.

Thread-safe collection class

. NET provides us with a collection class which is one of our most commonly used tools. I hope this article will help you better understand these collection classes. Of course, there are still some imperfections in my personal feelings. For example, HashTable and Binary Search Tree are not detailed, including the comparison between one-way and two-way linked lists. For more information, see.

 

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.