Skip to content

Instantly share code, notes, and snippets.

@mr5z
Last active June 17, 2019 09:24
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mr5z/052573d34a8e2e33ceb237d34ef6665b to your computer and use it in GitHub Desktop.
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