Self-writing a imitation dictionary and foreach realization and experience Summary _ practical skills

Source: Internet
Author: User
Tags what interface
Write yourself a class imitating dictionary implementation
A, custom dictionary class Mydic
Copy Code code as follows:

Using System.Collections.Generic;
namespace _10_ himself write 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 Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Diagnostics;
Using System.IO;
Using System.Linq;
Using System.Text;
namespace _10_ himself write dictionary {
Class Program {
static void Main (string[] args) {
Dictionary method implementation
dictionary<string, string> dic = new Dictionary <string, string> ();
string[] Filecon = File. ReadAllLines ("TXT format of English-Chinese Dictionary", 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 ("the");
Sw. Stop ();
Console.WriteLine (SW. Elapsed);//00:00:00:0000055;
Write your own list implementation
Mydic mydic = new Mydic ();
string[] Filecon2 = File. ReadAllLines ("TXT format of English-Chinese Dictionary", 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 ("the");
SW2. Stop ();
Console.WriteLine (SW2. Elapsed);//00:00:00:0001287; how many times is it slow!!! Because dictionary is more than list. Dictionary Catalog
Console.read ();
}
}
}

b The test results show that you are not imitating what the. Net Framework provides.

A: There is a dictionary in the region where the key value pairs, each storage unit of this area has address number, according to the hashcode algorithm, the key value of the value of the keys to the address should be stored, the key value pair into the specified address can be. Find the key's address first, you can find the data. Find the room number according to key instead of looking in the room one by one. (*) or: When a kvp is applied, a fixed algorithm (hash algorithm) is used to compute the address of the KVP in terms of key. Take the time is also based on the key to find can quickly calculate the KVP store address.

The interview question often asks foreach to implement what interface is a very good answer, then we can imitate the implementation of foreach?
C, foreach Internal principle: IEnumerable interface to achieve their own IEnumerable
Copy Code code as follows:

Using system.collections;//introduces IEnumerable namespace
Namespace Ienumerater {
Class Mylist:ienumerable {//implementation interface IEnumerable its method of declaring an enumerator on a IEnumerator
ArrayList ary = new ArrayList ();
public void Add (string name) {
ary. ADD (name);
}
Write your own indexer in the form of a property similar to an enumeration a quick and easy way to access elements in a collection
public string this[int index] {//int type
get {
Return Ary[index]. ToString ();
}//index>ary. Count is outside index bounds
set {}
}
public int this[String name] {//string type determines the return type by name lookup index parameter type decide for 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 you can see that foreach only allows data to be read, not to modify data
for (int i = 0; i < ary. Count; i++) {
Yield return ary[i]. ToString ();//The yield keyword can see the reason why foreach cannot modify a value by implementing the MoveNext (pointing to the next) method and current in the IEnumerator (enumerator) interface (getting the present element because there is only get) ) and reset Reset Index
}
}
}
}

D, call your own IEnumerable
Copy Code code as follows:

Using System;
Namespace Ienumerater {
Class Program {
static void Main (string[] args) {
Write yourself a class that implements the GetEnumerator () method of the IEnumerable interface to implement a foreach operation
MyList MyList = new MyList ();
MyList. Add ("Wanghao");/Call 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"; Cannot use foreach to change values
}
Console.read ();
}
}
}

Summary
If a class is foreach, the class must implement IEnumerable, the collection to support the traversal of the Foreach method, the IEnumerable interface must be implemented (and some way to return the object that implements the IEnumerator)

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.