Grouping strings by their first letter and ToDictionary implementation

Source: Internet
Author: User

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.

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.