. Net (C #): add the trygetvalue method of the dictionary to the keyedcollection type.

Source: Internet
Author: User

The trygetvalue method is very commonly used. You can convert the "judgment key existence" and "according to the key value" steps into one step. In this way, the hash value of the key is calculated only once, which is very efficient. Note that the idictionary interface does not define trygetvalue, while the generic interface idictionary <t, V> defines trygetvalue. The keyedcollection type inherits from the collection type <t>, and the collection <t> inherits from the icollection interface <t>. The reason should be that keyedcollection is not just a dictionary, but also a linear table. Therefore, keyedcollection does not have trygetvalue by default.

 

However, keyedcollection has a protected member: dictionary attribute. A generic idictionary is returned to represent the internal dictionary. Therefore, you can call the trygetvalue of the internal idictionary to rewrite the keyedcollection.

 

For example, first define a simple type: student. The ID attribute is the member key.

Class student

{

Public int ID {Get; set ;}

Public string name {Get; set ;}

}

 

Keyedcollection is defined as follows:

// + Using system. Collections. objectmodel;

Class mykeyedcollection: keyedcollection <int, student>

{

// Auxiliary Addition Method

Public void add (int id, string name)

{

Add (new student () {id = ID, name = Name });

}

 

// Rewrite the abstract method: getkeyforitem

Protected override int getkeyforitem (student item)

{

Return item. ID;

}

 

// Explicitly define the trygetvalue of the protected idictionary

Public bool trygetvalue (INT key, out student value)

{

Return dictionary. trygetvalue (Key, out value );

}

}

 

Sample Code:

VaR DIC = new mykeyedcollection ();

 

Dic. Add (3, "Martin ");

Dic. Add (1, "Tony ");

Dic. Add (2, "Liu ");

 

Student st;

If (DIC. trygetvalue (1, out st ))

Console. writeline (St. Name );

Else

Console. writeline ("not found ");

 

Output:

Tony

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.