酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C#利用Dictionary实现多城市电话区号查询:输入区号精准定位城市

下面是给出的一个相应实现的示例代码: ```csharp using System; using System.Collections.Generic; namespace phone { class Program { static void Main(string[] args) { Dictionary<string, City> phoneBook = new Dictionary<string, City>(); // 添加5个电话实例到Dictionary City city1 = new City("010", "北京"); phoneBook.Add(city1.AreaCode, city1); City city2 = new City("021", "上海"); phoneBook.Add(city2.AreaCode, city2); City city3 = new City("0755", "深圳"); phoneBook.Add(city3.AreaCode, city3); City city4 = new City("027", "武汉"); phoneBook.Add(city4.AreaCode, city4); City city5 = new City("020", "广州"); phoneBook.Add(city5.AreaCode, city5); Console.WriteLine("请输入电话号码:"); string phoneNumber = Console.ReadLine(); bool areaCodeExists = false; foreach (var kvp in phoneBook) { if (phoneNumber.StartsWith(kvp.Key)) { Console.WriteLine($"电话号码 {phoneNumber} 属于城市 {kvp.Value.CityName}"); areaCodeExists = true; break; } } if (!areaCodeExists) { Console.WriteLine("该区号不存在"); } } } class City { public string AreaCode { get; private set; } public string CityName { get; private set; } public City(string areaCode, string cityName) { AreaCode = areaCode; CityName = cityName; } } } ``` 注意,上述代码是一个简化的示例,只添加了5个城市的数据,如果你想要更多城市的电话号码数据,只需要继续按照相同的格式添加到Dictionary中即可。 ######[AI写代码神器 | 1243点数解答 | 2024-06-02 20:24:19]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]