Skip to content

Instantly share code, notes, and snippets.

@mr5z

mr5z/get_city.cs

Last active Jun 17, 2019
Embed
What would you like to do?
get cities from some country
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