The idea is as follows:
1. Use the Hashtable (efficient) set to record the number of times each word appears
2. Use ArrayList to sort Keys in Hashtable in alphabetical order.
3. sort by insert (stable)
Public void StatisticsWords (string path) {if (! File. Exists (path) {Console. WriteLine ("the File does not exist! "); Return;} Hashtable ht = new Hashtable (StringComparer. ordinalIgnoreCase); StreamReader sr = new StreamReader (path, System. text. encoding. UTF8); string line = sr. readLine (); string [] wordArr = null; int num = 0; while (line. length> 0) {// MatchCollection mc = Regex. matches (line, @ "\ B [a-z] +", RegexOptions. compiled | RegexOptions. ignoreCase); // foreach (Match m in mc) // {// if (ht. containsKey (m. value) // {// num = Convert. toInt32 (ht [m. value]) + 1; // ht [m. value] = num; //} // else // {// ht. add (m. value, 1); //} // line = sr. readLine (); wordArr = line. split (''); foreach (string s in wordArr) {if (s. length = 0) continue; // remove punctuation line = Regex. replace (line, @ "[\ p {P} *]", "", RegexOptions. compiled); // Add words to the hash table if (ht. containsKey (s) {num = Convert. toInt32 (ht [s]) + 1; ht [s] = num;} else {ht. add (s, 1) ;}} line = sr. readLine ();} ArrayList keysList = new ArrayList (ht. keys); // sort Keys in Hashtable in alphabetical order. sort (); // Sort by number of inserts [stable sorting], so the words with the same number of times are still in alphabetical order string tmp = String. empty; int valueTmp = 0; for (int I = 1; I <keysList. count; I ++) {tmp = keysList [I]. toString (); valueTmp = (int) ht [keysList [I]; // times int j = I; while (j> 0 & valueTmp> (int) ht [keysList [j-1]) {keysList [j] = keysList [j-1]; j --;} keysList [j] = tmp; // j = 0} // print out foreach (object item in keysList) {Console. writeLine (string) item + ":" + (string) ht [item]) ;}}