A detailed explanation of lookup class and ordered dictionary in C #

Source: Internet
Author: User

The

Lookup class describes

Dictionary<tkey,tvalue>, which supports only one value for each key. The new class lookup<tkey,tvalue> is. NET3.5, it is similar to the DICTIONARY<TKEY,TELEMENT> This class is implemented in both the program and the System.core, defined with the System,linq namespace. The methods and properties of the

Lookup<tkey,telement> are as follows:

Property name or method name


Description

Count
     The

Property count returns the number of elements in the collection

Item
    

Use indexers to access specific elements depending on the key. Because the same key can correspond to multiple values, So this property returns an enumeration of all the values

contain ()
    

Method contains () returns a Boolean value, based on the use of the key parameter to transfer an element,

Applyresultselector ()
    

Applyresultselector (0 converts each entry according to the conversion function passed to it, returns a collection

Loopup <TKey,TElement> cannot be created as a common dictionary, and must Invoke Method ToLookup (), which returns a Lookup<tkey,telement> object. Method ToLookup () is an extension method, All classes that can be used to implement ienumerable<t>.

When a key requires a multiple value case ToLookup method is useful, ToLookup returns a special data structure, similar to group in SQL, that can be grouped together and indexed to access these elements, case:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;   Namespace lookup class {      class program     {         static void main (String[] args)          {            // Creates an array of type string             string[] array
 = {  "Cat", "dog", "Horse"};             //Build Lookup Structure              var lookup = array. ToLookup (Item => item.
Length);             //enum character length 3 string              foreach  (var item in lookup[3])              {               
 console.writeline ("3 = " +item);             }                //enum character length 5 string              foreach  (var item in lookup[5])              {            
    console.writeline ("5 = "  + item);             }              //Enumeration grouping   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;  foreach  (var grouping in lookup)              {             
   console.writeline ("grouping : ");                 foreach  ( var item in grouping)                  {              
      console.writeline (item);                 }              }         
    console.readkey ();         }            &nbsp}} 


The above case is grouped by the string length of the array elements, that is, the key of the element with the same character length is the same, and the index subscript is the same. For example, access through lookup[3], and horse to be accessed with lookup[5].


Ordered dictionary

The Sorteddictionary<tkey,tvalue> class is a binary search tree in which elements are sorted according to the key. The key type must implement the Icomparable<tkey> interface. If the type of the key cannot be sorted, You can also create a comparer that implements the Icomparer<tkey> interface and use the comparer as a parameter to the constructor of an ordered dictionary.

The Sorteddictionary<tkey,tvalue> class and the Sortedlist<tkey,tvalue> class are similar in functionality. But because sortedlist<tkey,tvalue> Implemented as an array based list, and the Sorteddictionary<tkey,tvalye> class is implemented as a dictionary, so they have different characteristics:

The 1.sortedlist<tkey,tvalue> class uses less memory than the Sorteddictionary<tkey,tvalue> class

2.sorteddictionary<tkey,tvalue> class is faster to insert and delete elements

3. When populating the collection with the sorted data, it is quicker to modify the capacity,sortedlist<tkey,tvalue> class.


Case:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;   namespace  ordered dictionary {    class program     {         static void main (String[] args)          {            //sortedlist <TKey,TValue> Use less memory             // sorteddictionary<tkey,tvalue> element inserts and deletes faster              //key to implement Icomparable<in t> interface              SortedDictionary<EmployeeID, Person> sd = new SortedDictionary<
Employeeid, person> ();             sd. AdD (New employeeid (3), New person ("China",  "Zhang Fei",  40));             sd.
ADD (New employeeid),  new person ("China",  "Guan Yu",  43));             sd.
Add (New employeeid (4),  new person ("China",  "Liu Bei",  45));             sd.
ADD (New employeeid (5),  new person ("China",  "Zhuge Liang",  24));             sd.
ADD (New employeeid (1),  new person ("United States",  "Howell",  40));             sd.
ADD (New employeeid (0), New person ("USA",  "Obama",  40));             sd.
Add (New employeeid (210),  new person ("North Korea",  "golden Three Fat",  40));             sd.
ADD (New employeeid),  new person ("India",  "Indo-third",  40));                            foreach  (VAR&NBSP;ITEM&NBSP;IN&NBSP;SD)              {                 console.writeline (item. Key.id+ "," +item. Value.name);//key, positive order sort                
          console.readkey ();         }          public  Class employeeid : icomparable<employeeid>     {         public int id { get; private set; }         public  EmployeeID (int id)         {      
      this.ID = id; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}           public  int compareto (employeeid other)         {  
          return id.compareto (Other.ID);         }          public  Class person     {        public string  country { get; private set; }          public string name { get; private set; }         public int Age { get; private  SET;&NBSP}         public person (string country, string  name, int age)         {             this.
country = country;             this.
name = name;             this.
age = age;         }       }}


Note: The SortedList class uses less memory than the SortedDictionary class, but the SortedDictionary class is faster when inserting and deleting unsorted data.

Detailed analysis of SortedList and SortedDictionary classes of different, SortedList internal use array preservation, can only be regarded as an orderly linear table, and the SORTEDSICTIONARY internal structure is red black tree (this is a data structure, do not know how to go to Baidu).

SortedDictionary internal structure is a red-black tree, red-black tree of the balance of the two-tree, SortedList is an orderly linear table, the internal structure is array, using the two-point search method to improve efficiency. Look up, insert, delete the time complexity of the operation, all O (Logn) , but the difference of the internal structure leads to the actual operation of the performance differences.

SortedList and SortedDictionary Performance comparisons----Inserts

Because SortedList is saved with an array, each time the insert operation, the first use of binary lookup sent to find the corresponding position, after the position, SortedList will be the value of the position after the next move a position, empty out the current bit, and then insert the value, This process uses the Array.copy method, which is compared to lossy performance, and the code is as follows:

private void Insert (int index,tkey key,tvalue value)
{
...
if (index<this._size)
{
array.copy (this.keys.index,this.keys,index+1,this._size-index);
Array.copy (This.values,index,this.values,index+1,this._size-index);
}
...
}


SortedDictionary, when adding an operation, rotates the node only according to the characteristics of the red and black tree, maintaining balance and no call to Array.copy.

Test code: Loop an int, a random array of 100000, added with SortedList and SortedDictionary, respectively.

  Conclusion: SortedDictionary performance is superior to dortedlist in the case of a large number of additions.

 
SortedList and sorteddictionary performance Comparisons----Query

, the event complexity is O (Logn), and there is no additional operation in the source code that causes performance loss.

Tested: The two in the case of cyclic 10W, only dozens of milliseconds, you can see that the query operation performance is not significant.


SortedList and sorteddictionary performance comparisons----Delete

from the case of the add operation, it can be seen that because the SortedList uses an array for storing data internally, And the limitations of the array itself makes SortedList most of the add operation must drop AH with the Array.copy method, resulting in loss of performance, this situation also exists in the deletion operation. So it is: in the case of a large number of deletions, SortedDictionary performance is superior to SortedList.


Summary: SortedDictionary the internal use of red-black trees to store data, SortedList use arrays to store data, the query efficiency of the two, but due to the limitations of the array itself, in the case of a large number of add delete operations, SortedDictionary performance is superior to SortedList.

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.