What's a good data structure for a multiple-value primary key object?
This question can best be asked by example. Say I have a database table called "Car" with the following columns:
(Make*, Model*, NumberOfDoors*, Description, Price, Mileage, Color)
The 3-tuple of Make, Model, and NumberOfDoors makes up the unique primary key in the database. What I've done is made a "Car" class for each line item, but if I want to have a collection of cars objects in the form of
{(Particular make model and doorcount, count, current sales), ...}
where the first element of each item in the collection is the unique type of car, the second is the count (how many of that type I have), and the third element is any curent sales on that make-model-doorcount, I'm running into a data structure dilemma.
What I've been doing so far is making an struct that fits into a hashtable, as below:
//This will be the unique key for the hashtable
dim uniqueID as String = myCar.make + "@"开发者_如何学运维 + myCar.model + "@" + myCar.doorCount
//This is the structure that will hold the perinent info about that unique
//car type
Structure inventory
Dim count as Integer
Dim currentSales as String
End Structure
At this point I'd proceed to fill the hashtable from the database table, where the key to the hashtable is the uniqueID string, and the value is an instantiation of the "inventory" struct. This is (in my opinion) very inelegant though, especially the hacked together uniqueID for the hashtable. Is there a better data structure solution for objects that have a primary key consisting of multiple values?
You can use the actual class or structure as your primary key.
Just override GetHashCode and Equals - this allows you to use the object itself as the key in a Dictionary, with multiple values being taken into account.
Generally speaking I'm not a fan of composite primary keys. If possible, consider going with a numeric PK such as CarId which is an identity/autonumber. Then put a unique constraint on the Make, Model and NumberOfDoors columns.
精彩评论