Hi,
Create a business object to encapsulate the data:
class City
{
// use public properties instead
public int Zip;
public string Phone;
}
It depends on whether you want increased performance or less of a memory
footprint. There's a trade-off you'll have to make there. If you're
using the 2.0 framework and want a small memory footprint at the expense
of performance (although it shouldn't really matter anyway for relatively
large sets of data, depending on how frequently searches will be
performed):
class CityList
: System.Collections.ObjectModel.Collection<City>
{
public new City this[int zip]
{
get
{
foreach (City city in this)
if (city.Zip == zip)
return city;
throw new KeyNotFoundException(
"City not found with specified zip: " + zip);
}
}
public City this[string phone]
{
get
{
foreach (City city in this)
if (city.Phone == phone)
return city;
throw new KeyNotFoundException(
"City not found with specified phone: " + phone);
}
}
}
If you want to increase performance (at the expense of memory) you can
maintain two sorted indexes (List<T>) within the CityList class itself and
implement IList explicitly instead of inheriting it from Collection<T>.
One List<T> instance could be sorted by zip and the other by phone (call
the Sort method), and in each respective indexer you could call
BinarySearch instead of iterating over every item in the collection. Any
operation performed on one list must be performed on the other as well.
e.g., Clear, Add, Insert, Remove.
--
Dave Sexton
Podi said:
How to do this in C#?
I want to have a lookup table (hash) of city by zip code (integer) or
phone number (string), and it would look something like
x = book[94555]; // x == "Fremont"
x = book["510-818-8888"]; // x == "Fremont"
x = book[10002]; // x == "Manhattan"
x = book["212-966-1234"]; // x == "Manhattan"
Thanks,
P