get cities from some country
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Task<string> FindCity(string postalCode) | |
{ | |
var jsonStream = EmbeddedResourceHelper.FromResources("postal_codes.json"); | |
var dictionary = DeserializeStream<Dictionary<string, string>>(jsonStream); | |
if (dictionary.ContainsKey(postalCode)) | |
return Task.FromResult(dictionary[postalCode]); | |
var collectionRange = dictionary.Where(e => e.Key.Contains("-")); | |
var result = FindCityFromRangeRecords(postalCode, collectionRange); | |
return Task.FromResult(result); | |
} | |
static T DeserializeStream<T>(Stream stream) | |
{ | |
var serializer = new JsonSerializer(); | |
using (var reader = new StreamReader(stream)) | |
using (var json = new JsonTextReader(reader)) | |
{ | |
return serializer.Deserialize<T>(json); | |
} | |
} | |
static string FindCityFromRangeRecords(string postalCode, IEnumerable<KeyValuePair<string, string>> collectionRange) | |
{ | |
foreach (var entry in collectionRange) | |
{ | |
var keys = entry.Key.Split('-'); | |
var startRange = int.Parse(keys[0]); | |
var endRange = int.Parse(keys[1]); | |
var postalCodeInt = int.Parse(postalCode); | |
if (postalCodeInt >= startRange && postalCodeInt <= endRange) | |
return entry.Value; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment