Link to home
Start Free TrialLog in
Avatar of tatton777
tatton777Flag for United States of America

asked on

What is the coolest way to get data and compare against a value?

I am doing a project for a school that can only do business with clients who are within  certain ZipCodes. So I have a table called Users and a table called ValidZips.

I have set the Users Zip to a session variable called sv.Zip. Now what I need to do is load the data from ValidZips and compare sv.Zip against the list of Zips in ValidZips.

So far to accomplish something like this, I would create a local table, fill it with the values from ValidZips and then do a : foreach(DataRow r in Table.Rows) type thing.

I know that there are a lot of tools that I'm not using that c# offers, dataadapters, datasets, etc...

What would be the best technique to solve my problem. I would really like to get better at c# rather than just rehashing my current skills.

Thanks, Bill.
ASKER CERTIFIED SOLUTION
Avatar of mrichmon
mrichmon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Depending on load I may recommend pre-loading the table into a hashtable (note you would not want to use a foreach() etc as the operation would be O(n) as opposed to the hashtables O(1) ... but for a school project mrichmon is correct in that the SQL query would be the best option.
Avatar of Carl Tawn
As mrichmon mentioned it would be more efficient to run a query against the DB and have it filter the data. It would be even more efficient to create a Stored Procedure in the DB to do it for you.

However, if you want to use the brute-force method, then the best way would be to use a DataReader to quickly loop through all the records. DataReaders maintain a connection to the DB and only retrieve a single record at a time, so they have a much lower overhead than DataSets.
carl .. it would be no faster to use a sproc, please don't perpetuate the sproc efficiency myth it being dynamic sql and a sproc get their execution plans stored in the same cache (sql server).

In fact many are arguing that dynamic sql can actually be faster



Another approach would be to cache the zipcode table in a DataTable.   I assume that the table is rather small and the values wouldn't change very often (or at all).

So, you'd fill the DataTable using the normal DataAdapter's Fill() methdo, and then just use the DataTable's own Select() method to see if there was a match.  It'd be something like this:

DataRow[] foundRows =  SomeTable.Select( "Zip='" + UserZip + "'");

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatatableclassselecttopic.asp