Use the structure struct as the key of Dictionary & lt; TKey, TValue & gt;, tkeytvalue

Source: Internet
Author: User

Use the structure struct as the key of the Dictionary <TKey, TValue>, tkeytvalue

We often use simple data types, such as int as the key of the generic Dictionary <TKey, TValue>, but sometimes we want the custom data type to be the key of the Dictionary <TKey, TValue>, how to do it?

 

If we want to customize a struct type as the key, we must define a comparison class for implementing the IEqualityComparer <T> interface for this struct, and implement the two methods of this interface: Equals () method and GetHashCode () method. The former is used to compare whether two keys are equal, and the latter is used to obtain the hash value of the key.

 

Simulate this scenario: When we shop in a mall, we often need to store our belongings in a locker and then hold the key of the locker. Abstract The key into a key. However, a key of the struct type will be defined later, and the portable item will be abstracted as a value. All the lockers will be a Dictionary <TKey, TValue> a set of key-value pairs.

 

Define a key of the struct type and define a comparison class for the struct type.

public struct GoodsKey    {        private int _no;        private int _size;        public GoodsKey(int no, int size)        {            _no = no;            _size = size;        }        public class EqualityComparer : IEqualityComparer<GoodsKey>        {            public bool Equals(GoodsKey x, GoodsKey y)            {                return x._no == y._no && x._size == y._size;            }            public int GetHashCode(GoodsKey obj)            {                return obj._no ^ obj._size;            }        }    }

 

The portable items are abstracted as follows.

public class Goods    {        public int Id { get; set; }        public string Name { get; set; }    }

 

Client.

Class Program {static void Main (string [] args) {Dictionary <GoodsKey, Goods> list = new Dictionary <GoodsKey, Goods> (new GoodsKey. equalityComparer (); GoodsKey key1 = new GoodsKey (1,100); list. add (key1, new Goods () {Id = 1, Name = "watch"}); if (list. containsKey (key1) {Console. writeLine ("this cabinet is already in use ~~ ");} Else {Console. WriteLine (" this cabinet is currently empty ~~ ") ;}Console. ReadKey ();}}

Run, output: This cabinet is already in use ~~

 

In the preceding example, when instantiating a Dictionary <GoodsKey, Goods>, you must specify a comparison class EqualityComparer instance that implements IEqualityComparer <GoodsKey> In its constructor.

 

Although the struct type is implemented as the key of the Dictionary <TKey, TValue>. However, there are some "packing and unpacking" that can be avoided. For the optimization scheme, refer to Jeffrey Zhao's blog post, here.


Dictionary <TKey, TValue>?

Dictionary <TKey, TValue>?
Similar to: Dictionary <object, object> is a type. The previous data type is equivalent to the contact query method, followed by the specific information that matches it.

You can think of TKey as an ID card number, and TValue as a person.

We retrieve this person based on the ID card number.
Reference: MSDN

In Dictionary <TKey, TValue>, TValue is passed into a class. How can this problem be defined?

The base class of the class is Object, that is, all classes inherit from the Object, so the code should be modified as follows:
Dictionary <int, object> openWith = new Dictionary <int, object> ();

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.