C # various generic collection experiences,

Source: Internet
Author: User

C # various generic collection experiences,

 

This article describes all other generic sets except Queue <T> and Stack <T>.

 

SortedList <TKey, TValue>

 

SortedList <TKey, TValue> is similar to List <T>. The difference is that elements in SortedList sets are sorted, when adding elements to the SortedList set, you need to add key-value pairs. When adding a set element, first use the "binary search algorithm" to locate the appropriate position, and then the element is placed in this position. All the collection elements after this position are removed from the whole.

 

        static void Main(string[] args)
        {
            var mySotedList = new SortedList<int, string>();
MySotedList. Add (1, "Zhang San ");
MySotedList. Add (2, "Li Si ");
MySotedList. Add (3, "Zhao Liu ");
MySotedList. Add (4, "Wang JIU ");
// Determine whether a key is included
            mySotedList.ContainsKey(1);
// Determine whether a value is included
MySotedList. ContainsValue ("Zhang San ");
// Obtain the index of a key
            int keyIndex = mySotedList.IndexOfKey(2);
// Obtain the index of a value
Int valIndex = mySotedList. IndexOfValue ("Li Si ");
// Delete by key
            mySotedList.Remove(3);
// Delete an index
            mySotedList.RemoveAt(1);
// Search for elements by key
            string myVal = mySotedList[3];
// Search for elements based on the index
            string myVal1 = mySotedList.Values[1];
// Search by index key
            int myKey = mySotedList.Keys[3];
// Get an element without throwing an exception
            string myWantVal;
            if (mySotedList.TryGetValue(2, out myWantVal))
            {
                
            }
// Traverse Key
            foreach (int key in mySotedList.Keys)
            {
                
            }
// Traverse Value
            foreach (string str in mySotedList.Values)
            {
                
            }
        }

 

The disadvantage of using SortedList <TKey, TValue> is that when data is inserted, the Insert Location is determined by the "binary search algorithm", which is expensive. However, sortedList <TKey, TValue> sets are sorted in ascending order, which makes searching easier.

 

You can use SortedList <TKey, TValue> if you need to perform regular searches for a set and insert a small number of data into the set.


Dictionary <TKey, TValue>

 

Dictionary <TKey, TValue> stores the stored data in a HashTable. The keys of each set element must be unique and the Set elements are not sorted.
Similar to SortedList <TKey, TValue>, a set element is added in the form of a key-value pair. The difference is that the efficiency of data insertion is Dictionary <TKey, TValue> is higher than SortedList <TKey, TValue>.


            var myDictionary = new Dictionary<int, string>();
            myDictionary.Add(1, "darren");
            myDictionary.Add(2, "jack");
            myDictionary.Add(3, "sunny");
// Determine whether the object exists based on the key
            myDictionary.ContainsKey(1);
// Determine whether the object exists based on the Value
            myDictionary.ContainsValue("darren");
// Delete by key
            myDictionary.Remove(3);
// Search for set elements by key
            string myVal = myDictionary[2];
// No exception is thrown when searching for elements by key
            string myVal1;
            if (myDictionary.TryGetValue(2, out myVal1))
            {
                
            }
// Traverse Key
            foreach (int key in myDictionary.Keys)
            {
                
            }
// Traverse Value
            foreach (string value in myDictionary.Values)
            {
                
            }

 

SortedDictionary <TKey, TValue>

 

 

SortedDictionary <TKey, TValue> and SortedList <TKey, TValue>. The biggest difference is that SortedDictionary <TKey, TValue> cannot obtain collection elements through indexes, it maintains a "red and black tree" internally. Therefore, when performing the insert operation, SortedDictionary <TKey, TValue> and SortedDictionary <TKey, TValue> have better execution efficiency than SortedList <TKey>, of course, it also occupies more memory.

 

           var mySortedDictionary = new SortedDictionary<int, string>();
            mySortedDictionary.Add(1,"one");
            mySortedDictionary.Add(2,"two");
            mySortedDictionary.Add(3,"three");
// Determine whether a key is included
            mySortedDictionary.ContainsKey(2);
// Determine whether a value is included
            mySortedDictionary.ContainsValue("two");
// Remove an element based on the key
            mySortedDictionary.Remove(2);
// Search for an element by key
            string myVal = mySortedDictionary[1];
// Search for elements by key without throwing an exception
            string myVal1;
            if (mySortedDictionary.TryGetValue(1, out myVal1))
            {
                
            }
// Traverse all keys
            foreach (int key in mySortedDictionary.Keys)
            {
                
            }
// Traverse all values
            foreach (string val in mySortedDictionary.Values)
            {
                
            }

 

Revoke list <T>

 

Each set element has an attribute that refers to the forward and next nodes. The first node is the last node, and the last node is the second node. The first and last nodes of the last node are the second and last nodes.


           var myLinkedList = new LinkedList<string>();
// Create the first node
            myLinkedList.AddFirst("one");
// Create the last Node
           var lastNode = myLinkedList.AddLast("three");
// Add a node before the last Node
            myLinkedList.AddBefore(lastNode, "two");
// Add a node after the last Node
            myLinkedList.AddAfter(lastNode, "four");
// Traverse node values
            foreach (string value in myLinkedList)
            {
                
            }
// Search nodes by value
// Find the first node that meets the conditions
            var myNode = myLinkedList.Find("two");
// Search nodes by value
// Find the last node that meets the conditions
            var myNode1 = myLinkedList.FindLast("one");
// Obtain the first node
            var firstNode = myLinkedList.First;
// Obtain the last Node
            var lastNode1 = myLinkedList.Last;
// Generate nodes by value
            myLinkedList.Remove("one");
// Delete the first node
            myLinkedList.RemoveFirst();
// Delete the last Node
            myLinkedList.RemoveLast();
// Clear all nodes
            myLinkedList.Clear();
 

 

If you have many insert operations on a set, or insert batch set elements, you can consider using the sequence list <T>.

 

SortedSet <T>

 

SortedSet <T> is actually of the SortedDictionary type, but has no key and only a value. SortedSet indicates an abstract dataset. The element values in the dataset must be unique and unsorted.

To merge a group of data, you can use SortedSet <T>.

 

            var sortedSet1 = new SortedSet<string>();
            sortedSet1.Add("one");
            sortedSet1.Add("two");
            sortedSet1.Add("three");
            var sortedSet2 = new SortedSet<string>();
            sortedSet2.Add("two");
            sortedSet2.Add("four");
// Determine whether a value exists
            sortedSet1.Contains("one");
// Merge datasets to retrieve repeated items
            sortedSet1.ExceptWith(sortedSet2);
// Determine whether a dataset is its own
            sortedSet1.IsSubsetOf(sortedSet2);
// Determine whether a dataset contains all elements of another Dataset
            sortedSet1.IsSubsetOf(sortedSet2);
// Determine whether two datasets have an intersection
            sortedSet1.Overlaps(sortedSet2);
// Delete an element by value
            sortedSet1.Remove("two");
// Determine whether two datasets are equal
            sortedSet1.SetEquals(sortedSet2);
// Only contains elements in one dataset. These elements are not included in another dataset.
            sortedSet1.SymmetricExceptWith(sortedSet2);
// Obtain the union of two datasets
            sortedSet1.UnionWith(sortedSet2);
// Obtain a dataset containing certain elements
            SortedSet<string> result = sortedSet1.GetViewBetween("one", "two");
// Traverse the dataset
            foreach (string val in sortedSet1)
            {
                
            }
// Clear the dataset
            sortedSet1.Clear();

 

HashSet <T>

 

Both HashSet and SortedSet implement the ISet interface. To use SortedSet, you must use multiple element values as search conditions. data cannot be hashed. HashSet should be considered in other cases.

 

            var hashSet1 = new HashSet<string>();
            hashSet1.Add("one");
            hashSet1.Add("two");
            hashSet1.Add("three");
            var hashSet2 = new HashSet<string>();
            hashSet2.Add("two");
            hashSet2.Add("four");
// Determine whether a value is included
            hashSet1.Contains("four");
// Remove items that are duplicated in one dataset and in another Dataset
            hashSet1.ExceptWith(hashSet2);
// Keep the same items in one dataset as in another Dataset
            hashSet1.IntersectWith(hashSet2);
// Determine whether a dataset is a subset of another Dataset
            hashSet1.IsSubsetOf(hashSet2);
// Determine whether a dataset contains all elements of another Dataset
            hashSet1.IsSupersetOf(hashSet2);
// Determine whether two datasets have repeated Elements
            hashSet1.Overlaps(hashSet2);
// Delete an element by value
            hashSet1.Remove("one");
// Determine whether two datasets are equal
            hashSet1.SetEquals(hashSet2);
// Merge two datasets
            hashSet1.UnionWith(hashSet1);
// Search for elements that are only contained in one dataset but not in another Dataset
            hashSet1.SymmetricExceptWith(hashSet2);
// Traverse the dataset
            foreach (string value in hashSet1)
            {
                
            }
// Clear the dataset
            hashSet1.Clear();

 

 

In the past few days, I have experienced the usage of various generic sets. Summary:

 

● Stack <T> comes out first, here.
● Queue <T> first-in-first-out, here.

● SortedList <TKey, TValue>. Data is not inserted frequently and needs to be searched frequently.
● Dictionary <TKey, TValue>, usually inserts data, not sorted, and key-value pairs.
● SortedDictionary <TKey, TValue>, often inserts data, sorts, and key-value pairs.
● Random list <T>, two-way linked list, and arbitrary insertion.
● SortedSet <T>: a dataset. Multiple element values are used as search conditions. data cannot be hashed.
● HashSet <T>: DataSet. In most cases, HashSet is used to process dataset operations.

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.