Self-writing a Dictionary and Foreach imitation implementation and summary

Source: Internet
Author: User

Write a class by yourself to simulate the Dictionary implementation
A. custom dictionary class MyDic
Copy codeThe Code is as follows:
Using System. Collections. Generic;
Namespace _ 10 _ write your own Dictionary {
Class KeyValuePair {
Public KeyValuePair (){
}
Public KeyValuePair (string key, string value ){
This. key = key;
This. value = value;
}
Private string key;
Public string Key {
Get {
Return key;
}
Set {
Key = value;
}
}
Private string value;
Public string Value {
Get {
Return this. value;
}
Set {
This. value = value;
}
}
}
Class MyDic {
List <KeyValuePair> list = new List <KeyValuePair> ();
Public void Add (string key, string value ){
List. Add (new KeyValuePair (key, value ));
}
Public bool ContainsKey (string key ){
Bool res = false;
Foreach (KeyValuePair item in list ){
If (item. Key = key ){
Res = true;
Break;
}
}
Return res;
}
}
}

B. Call Test
Copy codeThe Code is as follows:
Using System;
Using System. Collections. Generic;
Using System. Diagnostics;
Using System. IO;
Using System. Linq;
Using System. Text;
Namespace _ 10 _ write your own Dictionary {
Class Program {
Static void Main (string [] args ){
// Implementation of the Dictionary Method
Dictionary <string, string> dic = new Dictionary <string, string> ();
String [] filecon = File. ReadAllLines ("English dictionary TXT", Encoding. Default );
For (int I = 0; I <filecon. Count (); I ++ ){
String [] arr = filecon [I]. Split (new char [] {''}, StringSplitOptions. RemoveEmptyEntries );
If (! Dic. ContainsKey (arr [0]) {
Dic. Add (arr [0], arr [1]);
}
}
Stopwatch sw = new Stopwatch ();
Sw. Start ();
Dic. ContainsKey ("china ");
Sw. Stop ();
Console. WriteLine (sw. Elapsed); // 00: 00: 00: 0000055;
// Self-written list implementation
MyDic mydic = new MyDic ();
String [] filecon2 = File. ReadAllLines ("English dictionary TXT", Encoding. Default );
For (int I = 0; I <filecon2.Count (); I ++ ){
String [] arr = filecon2 [I]. Split (new char [] {''}, StringSplitOptions. RemoveEmptyEntries );
If (! Mydic. ContainsKey (arr [0]) {
Mydic. Add (arr [0], arr [1]);
}
}
Stopwatch sw2 = new Stopwatch ();
Sw2.Start ();
Mydic. ContainsKey ("china ");
Sw2.Stop ();
Console. WriteLine (sw2.Elapsed); // 00: 00: 00: 0001287; how many times have you slowed down !!! Because dictionary has more dictionary directories than list.
Console. Read ();
}
}
}

The test result in B shows that the imitation is not as fast as that provided by. Net FrameWork. Why?

A: A Dictionary has a region for storing key-value pairs. Each storage unit in this region has an address number. Based on the hashCode algorithm, the address that should be stored for calculating the key-value pairs, put the key-value pair to the specified address. When searching, you can find the data by calculating the key address. Find the room number based on the key instead of the room number. (*) Or: When a kvp is used, a fixed algorithm (hash algorithm) is used to calculate the address of the kvp based on the key. The kvp storage address can be quickly calculated based on the key to be searched.

In the interview questions, I often ask Foreach what interfaces are implemented. This is a good answer. Can we simulate and implement Foreach on our own?
C. Internal principles of Foreach: IEnumerable interface implements IEnumerable
Copy codeThe Code is as follows:
Using System. Collections; // introduce the namespace of IEnumerable
Namespace IEnumerater {
Class MyList: IEnumerable {// The implementation interface IEnumerable, which declares the enumeration method for an IEnumerator.
ArrayList ary = new ArrayList ();
Public void Add (string name ){
Ary. Add (name );
}
// The form of self-writing indexer is similar to that of an attribute. Similar to enumeration, you can easily and quickly access elements in a set.
Public string this [int index] {// int type
Get {
Return ary [index]. ToString ();
} // Index> ary. Count exceeds the index Limit
// Set {}
}
Public int this [string name] {// The string type is queried by name. The index parameter type is determined by yourself. The return type is determined by yourself.
Get {
For (int I = 0; I <ary. Count; I ++ ){
If (ary [I] = name ){
Return I;
}
}
Return-1;
}
}
Public IEnumerator GetEnumerator () {// IEnumerator F12 jump definition here we can find that foreach can only read data, but cannot modify data
For (int I = 0; I <ary. Count; I ++ ){
Yield return ary [I]. toString (); // yield keyword. You can see MoveNext (pointing to the next one) in the Implementation IEnumerator (enumerator) interface) method and Current (get the Current element because only get can be understood why foreach cannot modify the value) and Reset to Reset the index
}
}
}
}

D. Call your own IEnumerable
Copy codeThe Code is as follows:
Using System;
Namespace IEnumerater {
Class Program {
Static void Main (string [] args ){
// Write a class to implement the getEnumerator () method of the IEnumerable interface to implement the foreach operation.
MyList mylist = new MyList ();
Mylist. Add ("wanghao"); // call your own add (string) Method
Mylist. Add ("nihao ");
Mylist. Add ("buhao ");
Console. WriteLine (mylist [1]); // use your own index
Console. WriteLine (mylist ["nihao"]. ToString ());
Foreach (string item in mylist ){
Console. WriteLine (item );
// Item = "hello"; you cannot use foreach to change the value.
}
Console. Read ();
}
}
}

Summary:
If a class performs foreach, the class must implement IEnumerable. To support the foreach traversal, the set must implement the IEnumerable interface (and return the object that implements IEnumerator in some way)

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.