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
Let's take a look at what interfaces the FCL provides for us:
IEnumerable and Ienumberator
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.
public interface ienumerable{ 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.
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 usi Ng 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:
Support for foreach statements
Interacting with other class libraries as a standard collection class
Meet the requirements of a more complex collection interface
Support for collection initializers
Of course there are many ways to implement it, as follows:
If our collection comes from encapsulating other collection classes, then we can return directly to the enumerator of this collection
Return by yield return
Implement our own IEnumerator to achieve
Here is a demonstration of how yield can be implemented 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 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:
Statistics set and number of elements
Get the subscript of an element
Determine if there is
Add an element to the end
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:
Dictionary<tkey,tvalue>
Sorteddictionary<tkey,tvalue>
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.
List<t>
Linkedlist<t>
Hashset<t>
Sortedset<t>
Stack<t>
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.
Arrarylist
Later replaced by List<t>.
HashTable was later replaced by Dictionary<tkey,tvalue>.
The Queue was later replaced by Queue<t>.
SortedList was later replaced by Sortedlist<t>.
The Stack was later replaced by Stack<t>.
Thread-Safe Collection classes
Concurrentqueue thread-safe version of the queue
Concurrentstack thread-safe version of the stack
Concurrentbag Thread-Safe collection of objects
Concurrentdictionary Thread-Safe dictionary
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.