0

I have a database that I load with EntityFramework.

In this database there is a table that contains a couple of columns. 2 of those columns are called ZipcodeFrom and ZipcodeTill. The Zipcodes in the table are from different countries, so there is no real standard format.

The problem I have now is the following.

I receive a Zipcode and I need to find the row which contains the Zipcode range associated with the received Zipcode.

I can't use SQL to use the BETWEEN function. So I'm looking for a BETWEEN function for C# if (Zipcode BETWEEN ZipcodeFrom and ZipcodeTill)

9
  • Can you show sample data? Commented Apr 23, 2015 at 8:43
  • How do you define what is in that range? Commented Apr 23, 2015 at 8:43
  • What have tried? Add sample code to your question. Commented Apr 23, 2015 at 8:43
  • 2
    @jonamreddy loading an entire zipcode database is not a good idea, typically - perhaps unless you're using a file based library Commented Apr 23, 2015 at 8:45
  • 1
    It really all depends on the format of the Zipcodes and when you define a Zipcode to be "between" two other zipcodes. For example: a dutch zipcode consists of 4 numbers followed by two letters. Would 1234BC be between 1234BB and 1234 BD? And would it be between 1234AC and 1234CC? The best way in my opinion would be to treat a zipcode as a base-36 number and do your work based on that, but do all zipcodes follow a format where they are build up out of just numbers and letters? Commented Apr 23, 2015 at 8:48

1 Answer 1

1

Assuming you are doing this alphabetically, this effectively mimics a SQL BETWEEN operation:

var zipCode = "SOMECODE";

var result = from row in db.Table
             where row.ZipcodeFrom <= zipCode
             && row.ZipcodeTo >= zipCode;

If your provider doesn't support using <, <=, > and >= operators, you should be able to use string.Compare instead:

var result = from row in db.Table
             where string.Compare(row.ZipcodeFrom, zipCode) <= 0
             && string.Compare(row.ZipcodeTo, zipCode) >= 0;
Sign up to request clarification or add additional context in comments.

1 Comment

The problem here is that when i do this the following error occurs because i'm comparing strings: Operator >= cannot be applied to operands of type string and string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.