This is Ctrip (Shenzhen ). net development test a question, requires the implementation of strings grouped by the first letter and ToDictionary output, was not made at that time, later studies, now will be the implementation of this question several methods down.
First, initialize the data source, which is a List <string> object. The following code.
// Data source List <string> list = new List <string> {"Beijing", "Shanghai", "Tianjin", "Chongqing", "Harbin", "Dalian ", "Qingdao", "Xi 'an", "Dunhuang", "Nanjing", "Wuxi", "Suzhou", "Yangzhou", "Zhenjiang", "Hangzhou ", "Xitang", "Zhoushan", "Chun 'an", "Qiandaohuzhen", "Shaoxing", "Huangshan", "Jiujiang", "Xiamen", "Wuyi Shan ", "Zhangjiajie", "Chengdu", "Shenzhen", "Zhuhai", "Guangzhou", "Guilin", "Kunming", "Xishuangbanna", "Dali", "Lijiang ", "Guiyang", "Urumqi", "Turpan", "Lhasa "};
The first grouping method uses a regular expression. The Code is as follows.
/// <Summary> /// use a regular expression to match. /// </summary> /// <param name = "str"> </param> /// <returns> </returns> private static string GetGroupNameByRegex (char str) {string sInput = str. toString (); if (Regex. isMatch (sInput, "[a-gA-G]", RegexOptions. ignoreCase) {return "A-G";} if (Regex. isMatch (sInput, "[h-nH-N]", RegexOptions. ignoreCase) {return "H-N";} return "O-Z ";}
The second method compares two char directly. The Code is as follows.
/// <Summary> /// Method 2: use the ASCII code to match the characters /// </summary> /// <param name = "str"> </param> /// <returns> </returns> private static string GetGroupNameByCharASCII (char str) {if (str> = 'A' & str <= 'G') | (str> = 'A' & str <= 'G ')) // char can be implicitly converted to int {return "A-G";} if (str> = 'H' & str <= 'n ') | (str> = 'H' & str <= 'n') {return "H-N";} return "O-Z ";}
Note: The reason why two char values can be directly compared is that char is converted to an int value, that is, the corresponding ASCII code, and then compared to the size.
The third method is actually the same as the second method, but is optimized based on method 2. The Code is as follows.
/// <Summary> /// upgrade method 2 /// </summary> /// <param name = "str"> </param> /// <returns> </returns> private static string GetGroupNameByCharASCII1 (char str) {char newChar = Char. toLower (str); // if (newChar> = 'O') // {// return "O-Z"; //} // if (newChar> = 'H ') // {// return "H-N"; //} // return "A-G"; return newChar> = 'O '? "O-Z": newChar> = 'H '? "H-N": "A-G ";}
It should be noted that, in method 3, multiple if... else... statements can be simplified using the ternary operator to make the code more elegant.
Output result. The Code is as follows.
var query = list.GroupBy(p =>{ return GetGroupNameByRegex(p[0]);}).ToDictionary(p => p.Key, p => p);foreach (var item in query){ Console.WriteLine("{0}", item.Key);//IGrouping<TKey,TValue> foreach (var subItem in item.Value) { Console.WriteLine(" {0}", subItem); }}Console.ReadKey();
The output result is as follows.