Sorting UK Postcodes with C#

19 11 2012

Ok, before you say anything, yes I know. It has been a long time since I posted anything remotely useful here. Well in my last job I ended up doing less development and more team management so the useful bits I came across were few and far between. In my new job I am back to development, so I should have more to post here in the future.

One of the requirements I had recently was to sort UK postcodes in ascending order. The postcodes were being stored in a list of type IEnumerable and were all strings. As you are probably aware if you are searching for this, UK postcodes are alphanumeric (NP10, NP11 etc). This means that if you try and sort the following list of postcodes: NP1, NP23, NP35, NP3, NP2, NP45, NP11

You would get the outcome: NP1, NP11, NP2, NP23, NP3, NP35, NP45

However the outcome required is: NP1, NP2, NP3, NP11, NP23, NP35, NP45

I found this brilliant blog post which provides some code under the MIT license which does the job perfectly – Natural Sorting in C#

I included his EnumerableComparer class as a Utility class in my Framework and then used the code in a similar way to this:

IEnumerable<PostcodeAllocation> allocations = GetAllAllocations();
// Declare convert string as per IanG's blog post
Func<string, object> convert = str =>
{
try
{
return int.Parse(str);
}
catch
{
return str;
}
};
allocations.OrderBy(str => Regex.Split(str.Postcode.Replace(" ", ""), "([0-9]+)").Select(convert), new EnumerableComparer<object>());

This then sorts my data as follows: NP1, NP2, NP3, NP11, NP23, NP35, NP45.

Perfect! I hope this helps someone else and a huge thanks to IanG on his blog for this great snippet of code.

Advertisements